You are currently viewing Flutter 101: Getting Started

Flutter 101: Getting Started

Flutter is a tool made by Google that makes it easier to create apps for phones, computers, and websites using just one set of code. Instead of writing separate code for each device, Flutter lets developers build everything in one place and run it anywhere. In this article, you’ll learn what Flutter is, how to set it up on your computer, and how to build a simple app step by step. By the end, you’ll have a good start on your journey to making your own apps.

What is Flutter?

Overview of Flutter

Google Flutter, as it sometimes called, is a free and open-source tool created by Google that makes it easier to build apps for different devices, like phones, tablets, computers, and websites, all using the same code. Normally, developers have to write separate code for each type of device, but Flutter saves time by allowing them to create everything in one place. It uses a programming language called Dart, which was also made by Google. Flutter is popular because it helps developers design beautiful apps that run fast and smoothly on any platform.

Benefits of Using Flutter

Flutter makes app development easier and faster. Here’s why developers love it:

  • Cross-Platform Development: Instead of writing separate code for Android, iOS, web, and desktop, Flutter lets you write code once and run it everywhere.
  • Fast Development: With the hot reload feature, you can see changes instantly without restarting the app, making coding much quicker.
  • Expressive and Flexible UI: Flutter comes with ready-made widgets that help you create beautiful designs, and you can customize them however you like.
  • High Performance: Since Flutter compiles directly to native code, apps run smoothly and respond quickly, just like those built specifically for each platform.

Setting Up the Flutter Development Environment

Before you can start building apps with Flutter, you need to set up your development environment.

Installing Flutter SDK

  1. Download Flutter SDK: Go to the Flutter website and download the version that matches your operating system.
  2. Extract the Flutter SDK: Once downloaded, unzip or extract the file to a location where you want to keep Flutter on your computer.
  3. Set Up Your System Path: Add the flutter/bin folder to your system’s PATH variable so you can run Flutter commands from anywhere.

This setup ensures your computer is ready to create and run Flutter apps.

Setting Up an Editor

To write Flutter code, you can use any text editor or Integrated Development Environment (IDE). Two popular options are VS Code and Android Studio because they come with helpful tools for Flutter development.

  • VS Code: A lightweight and fast editor. To set it up for Flutter, install the Flutter and Dart extensions from the VS Code marketplace.
  • Android Studio: A more advanced IDE that includes everything needed for Android development. Install the Flutter and Dart plugins from the Android Studio plugin marketplace to enable Flutter support.

Both options provide features like code suggestions, debugging tools, and easy integration with Flutter commands. Choose the one that best fits your workflow.

Writing a Simple Flutter Application

Now that your environment is set up, let’s create and run a basic Flutter app.

  1. Create a New Flutter Project: Open your terminal or command prompt and run:
flutter create first_app

This command generates a new Flutter project with the necessary files.

  1. Navigate to the Project Directory: Move into the newly created project folder:
cd first_app

  1. Open the Project in Your Editor: Open the folder in VS Code or Android Studio to view and edit your project files.
  2. Run the Flutter Application: Start the app on a connected device or emulator with:
flutter run

After a few moments, you should see a basic Flutter app running. This is a great starting point to explore and customize your first Flutter project.

Flutter Getting Started [Image 1]

Understanding the Default Flutter Project Structure

When you create a new Flutter project, it comes with several folders and files. Here’s what they do:

  • lib/: This is where your app’s main code lives. The main.dart file inside this folder is the starting point of your Flutter app.
  • android/ & ios/: These folders contain platform-specific code for Android and iOS. Flutter uses these to run your app on different devices.
  • web/: If you enable Flutter for the web, this folder contains the files needed to run your app in a browser.
  • test/: This is where you write test scripts to check if your app is working correctly.
  • pubspec.yaml: This file manages your app’s dependencies, assets, and settings. You use it to add packages and resources to your project.
  • README.md: A simple file that gives information about your project.

Understanding this structure helps you know where to write code, add resources, and make changes to your Flutter app.

Understanding Flutter Architecture

Flutter Widgets

Widgets are the basic building blocks of a Flutter app. Everything you see on the screen — text, buttons, images, and even the entire layout—is made of widgets. Flutter provides many built-in widgets, and you can also create custom ones to build your app’s UI.

Flutter’s Reactive Framework

Flutter follows a reactive programming model, meaning the UI automatically updates when the app’s state changes. Instead of manually refreshing the screen, Flutter detects changes and updates the UI accordingly. This makes building dynamic and interactive apps easier.

The Widget Tree

Flutter arranges widgets in a widget tree, which represents the app’s UI structure. Each widget is either a parent (holding other widgets) or a child (nested inside another widget). The widget tree allows developers to design complex layouts by combining simple building blocks. Understanding this structure helps in organizing and managing UI components efficiently.

Creating Your First Flutter App

Let’s go step by step to build a simple Flutter app.

The main.dart File

The main.dart file is the starting point of your Flutter application. It contains the main function and the root widget that defines how your app looks and behaves.

Here’s a simple Flutter app:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('My First Flutter App')),
        body: const Center(
          child: Text('Hello, Flutter!'),
        ),
      ),
    );

  }
}

What’s Happening in the Code:

  • void main() => runApp(const MyApp()); starts the app and calls the MyApp widget.
  • MyApp extends StatelessWidget, meaning it does not change over time.
  • MaterialApp is the main wrapper for the app, providing basic app structure.
  • Scaffold gives the app a basic layout, including an AppBar and a body.
  • Center positions the Text widget in the middle of the screen.

Running the App

To see your app in action, open a terminal inside your project folder and run:

flutter run

This will build and launch the app on your emulator or connected device. You should see a simple app with a title bar and “Hello, Flutter!” displayed at the center.

Flutter Getting Started [Image 2]

Basic Flutter Widgets

Flutter provides many widgets to help build your app’s UI. Here are some essential ones:

Text Widget

The Text widget is used to display text (show words) on the screen.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Text Widget')),
        body: const Center(
          child: Text(
              'Hello, Flutter!',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)
          ),
        ),
      ),
    );
  }
}

This displays “Hello, Flutter!” in big, bold letters. You can change the size, color, and style to make the text look the way you want.

Flutter Getting Started [Image 3]

Container Widget

The Container widget is like a box that holds other widgets and can be styled. It helps with organizing the layout of your app.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Container Widget')),
        body: Center(
          child: Container(
            padding: const EdgeInsets.all(16),
            margin: const EdgeInsets.all(16),
            color: Colors.blue,
            child: const Text('Hello, Flutter!', style: TextStyle(color: Colors.white)),
          ),
        ),
      ),
    );
  }
}

In this example, the Container has:

  • Padding (space inside the box) of 16 pixels.
  • Margin (space outside the box) of 16 pixels.
  • A blue background.
  • A Text widget inside it that says “Hello, Flutter!” with white text.

This makes the text stand out inside a styled box.

Flutter Getting Started [Image 4]

Row and Column Widgets

The Row and Column widgets are used to organize other widgets in your app. They help you place things side by side (Row) or one on top of the other (Column).

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Container Widget')),
        body: const Center(
          child: Column(
            children: [
              Text('Item 1'),
              Text('Item 2'),
              Text('Item 3'),
            ],
          ),
        ),
      ),
    );
  }
}

In this example, the Column arranges the text widgets vertically (one on top of the other). A Row works the same but arranges items horizontally (side by side).

Flutter Getting Started [Image 5]

So, if you want a list to go down the screen, use Column, and if you want items to go across, use Row.

Image Widget

The Image widget is used to show pictures in your app.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Image Widget')),
        body: Center(
          child: Image.network('https://wallpapers.com/images/high/fan-art-mortal-kombat-epic-rivalry-fm4tg6j4fepjbv5u.webp'),
        ),
      ),
    );
  }
}

In this example, the Image.network loads an image from the internet and displays it on the screen. You can use it to show any picture from a URL. There’s also an Image.asset widget to display images that are stored locally in your project.

Flutter Getting Started [Image 6]

Icon Widget

The Icon widget is used to show small images or symbols (icons), like stars, hearts, or arrows.

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Icon Widget')),
        body: const Center(
          child: Icon(Icons.star, color: Colors.black),
        ),
      ),
    );
  }
}

In this example, the Icon widget displays a black star icon. You can change the color and type of the icon to match what you need for your app.

Flutter Getting Started [Image 7]

These basic widgets help you design your app by creating layouts and adding visual elements that make it more interactive and fun!

Building a Simple Layout

To create a simple layout, you can combine multiple widgets and use layout widgets like Center, Padding, and Expanded.

Combining Widgets

You can nest widgets inside one another to create more complex layouts. This helps you organize your app’s content in an easy-to-understand way.

Using Layout Widgets

  • Center: Centers its child widget on the screen.
  • Padding: Adds space (padding) around its child widget.
  • Expanded: Makes its child widget take up all available space.

Code Example: Simple Layout

Here’s a simple example of how to arrange things on the screen using Flutter:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Simple Layout')),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              const Text('Hello, Flutter!', style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold)),
              Container(
                padding: const EdgeInsets.all(16),
                margin: const EdgeInsets.all(16),
                color: Colors.blue,
                child: const Text('Hello, Flutter!', style: TextStyle(color: Colors.white)),
              ),
              const Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(Icons.star, color: Colors.yellow),
                  Icon(Icons.star, color: Colors.yellow),
                  Icon(Icons.star, color: Colors.yellow),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }
}

What’s Happening in the Code:

  • The Text widget displays some text.
  • The Container widget holds another Text widget with some padding and a blue background.
  • The Row widget arranges three yellow star icons horizontally.
  • The Center widget centers the entire Column widget on the screen, and the Column arranges everything vertically.
Flutter Getting Started [Image 8]

This simple layout demonstrates how to arrange and style multiple widgets together to build an interactive UI.

Stateful and Stateless Widgets

In Flutter, there are two main types of widgets: stateful and stateless.

Differences Between Stateful and Stateless Widgets

  • Stateless Widgets: These are widgets that do not change once they are built. They do not store any information or “state” that can change over time. For example, a button or a text label is usually a stateless widget.
  • Stateful Widgets: These widgets can change over time. They can store information (called state) and update what you see on the screen when that information changes. For example, a button that shows a count of how many times it’s been clicked is a stateful widget because the count (state) changes.

In simple terms:

  • Stateless Widgets stay the same.
  • Stateful Widgets can change as things happen in your app.

Creating Stateful Widgets

A stateful widget has two parts:

  1. The widget class: This is where the widget is defined.
  2. The state class: This holds the information (or state) that can change over time.

Here’s an example of how to create a stateful widget:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Stateful Widget')),
        body: const Center(
          child: MyStatefulWidget(),
        ),
      ),
    );

  }
}

class MyStatefulWidget extends StatefulWidget {

  const MyStatefulWidget({super.key});

  @override
  MyStatefulWidgetState createState() => MyStatefulWidgetState();

}

class MyStatefulWidgetState extends State<MyStatefulWidget> {

  int _counter = 0;

  void _incrementCounter() {

    setState(() {
      _counter++;
    });

  }

  @override
  Widget build(BuildContext context) {

    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text('Counter: $_counter'),
        ElevatedButton(
          onPressed: _incrementCounter,
          child: const Text('Increment'),
        ),
      ],
    );
  }
}

What’s Happening in the Code:

  • The MyStatefulWidget class creates a state object by calling createState().
  • The MyStatefulWidgetState class is where the state is kept. It has a variable _counter that starts at 0.
  • The _incrementCounter method increases the _counter by 1 each time it’s called and uses setState() to update the display.
  • In the build() method, we show the current counter and an ElevatedButton that calls _incrementCounter when pressed.
Flutter Getting Started [Image 9]

This way, the widget can update the counter every time the button is pressed, which changes the state and re-renders the UI!

Creating Stateless Widgets

A stateless widget is simpler because it only has one class that extends StatelessWidget.

Here’s an example:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(

      home: Scaffold(
        appBar: AppBar(title: const Text('Stateless Widget')),
        body: const Center(
          child: MyStatelessWidget(),
        ),
      ),

    );

  }
}

class MyStatelessWidget extends StatelessWidget {

  const MyStatelessWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text('I am a stateless widget');
  }

}

What’s Happening in the Code:

  • The MyStatelessWidget class extends StatelessWidget.
  • The build method is used to display a Text widget that says “I am a stateless widget”.

This widget doesn’t have any state to change, so it will always show the same text. It’s simple and stays the same once built.

Flutter Getting Started [Image 10]

Handling User Input

Flutter has many widgets that allow users to interact with your app. These widgets let users input data, tap buttons, or perform gestures.

Common Widgets for Handling Input

  • TextField: Lets users type text.
  • ElevatedButton: A clickable button that can trigger actions when pressed.
  • GestureDetector: Allows you to detect gestures like taps, swipes, or drags.

These widgets help you make your app interactive and respond to user actions!

TextField

The TextField widget lets users type in text, such as their name or any other information.

Here’s an example:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(

      home: Scaffold(
        appBar: AppBar(title: const Text('Input Widget')),
        body: const Padding(
          padding: EdgeInsets.all(12.0),
          child: Center(
            child: TextField(
              decoration: InputDecoration(
                border: OutlineInputBorder(),
                labelText: 'Enter your name',
              ),
            ),
          ),
        ),
      ),

    );

  }
}

What’s Happening in the Code:

  • The TextField widget shows a text box where users can type.
  • The InputDecoration adds a label (“Enter your name”) and a border around the text field.
Flutter Getting Started [Image 11]

This widget is great for getting input from users, like asking for their name or other details!

ElevatedButton

The ElevatedButton widget creates a button that can be pressed to trigger an action.

Here’s an example:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(

      home: Scaffold(
        appBar: AppBar(title: const Text('Button Widget')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              print('Button pressed');
            },
            child: const Text('Press Me'),
          ),
        ),
      ),

    );

  }
}

What’s Happening in the Code:

  • The ElevatedButton displays a button with the text “Press Me”.
  • When the button is pressed, it triggers the onPressed function, which prints “Button pressed” in the console.
Flutter Getting Started [Image 12]

This widget is useful for adding buttons to your app that perform actions when clicked!

GestureDetector

The GestureDetector widget is used to detect gestures like taps, swipes, and other touch actions.

Here’s an example:

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {

  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {

    return MaterialApp(

      home: Scaffold(
        appBar: AppBar(title: const Text('GestureDetector Widget')),
        body: Center(
          child: GestureDetector(
            onTap: () {
              print('Container tapped');
            },
            child: Container(
              color: Colors.blue,
              width: 100,
              height: 100,
            ),
          ),
        ),
      ),

    );

  }
}

What’s Happening in the Code:

  • The GestureDetector wraps around a Container widget.
  • When the container is tapped, the onTap function is triggered and prints “Container tapped” to the console.
Flutter Getting Started [Image 13]

This widget is great for detecting user interactions with elements like tapping, dragging, or swiping!

Conclusion

In this article, we learned about Flutter and why it’s great for making apps. We set up everything you need to start coding and built a simple app together. We also learned about widgets, which are the building blocks of a Flutter app, and how to make the app change when something happens, like when you press a button.

We also saw how to handle things like typing in text, pressing buttons, and tapping on the screen.

Now you have a good start with Flutter! There are lots of cool things to try, like using different widgets, creating different layouts, and making your app more interactive. Keep experimenting, and soon you’ll be making your own fun apps!

Leave a Reply