Getting Started with Flutter: A Beginner's Guide to Cross-Platform App Development

5.92K 0 0 0 0

📘 Chapter 3: Building Your First Flutter App

🧭 What You’ll Learn

In this chapter, you’ll build your first functional Flutter app step-by-step. You will learn how to:

  • Create a new Flutter project
  • Understand the default file and folder structure
  • Work with StatelessWidget and StatefulWidget
  • Use common UI widgets like AppBar, Text, Button, and Column
  • Add interactivity with user input and state changes
  • Run the app in emulator or real device
  • Structure code for readability and reuse

🚀 Getting Started with a New Flutter Project

Step 1: Create a Flutter App

Open your terminal or IDE and run:

bash

 

flutter create my_first_app

cd my_first_app

This generates a fully working starter app with everything set up.


Step 2: Run the App

Use an emulator or connect your device via USB and run:

bash

 

flutter run

You should see a simple app with a counter button.


📂 Understanding the Project Structure

File/Folder

Description

lib/

Main app logic and Dart code

lib/main.dart

The app's entry point

android/ & ios/

Native config for Android and iOS platforms

test/

Unit and widget tests

pubspec.yaml

Metadata, packages, and assets configuration


📘 Step-by-Step Breakdown of main.dart

Here’s what Flutter gives you by default:

dart

 

void main() {

  runApp(MyApp());

}

runApp() is the root of your Flutter app. It takes a widget (in this case, MyApp) and renders it on screen.


🧱 The MyApp Widget

dart

 

class MyApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      title: 'Flutter Demo',

      theme: ThemeData(primarySwatch: Colors.blue),

      home: MyHomePage(title: 'Flutter Home Page'),

    );

  }

}

  • MaterialApp: Provides navigation, themes, and scaffolding
  • ThemeData: Defines your app’s visual styling
  • MyHomePage: The home screen displayed after launch

🏗 The MyHomePage Stateful Widget

dart

 

class MyHomePage extends StatefulWidget {

  final String title;

  MyHomePage({Key? key, required this.title}) : super(key: key);

 

  @override

  _MyHomePageState createState() => _MyHomePageState();

}

  • StatefulWidget: A widget that can hold dynamic data
  • createState(): Connects the widget with its mutable state

🔁 The _MyHomePageState Class

dart

 

class _MyHomePageState extends State<MyHomePage> {

  int _counter = 0;

 

  void _incrementCounter() {

    setState(() {

      _counter++;

    });

  }

💡 Key Concepts:

  • _counter: Stores the app's state (counter value)
  • setState(): Tells Flutter to update the UI after changing state

📱 UI Layout in build()

dart

 

Widget build(BuildContext context) {

  return Scaffold(

    appBar: AppBar(title: Text(widget.title)),

    body: Center(

      child: Column(

        mainAxisAlignment: MainAxisAlignment.center,

        children: <Widget>[

          Text('You have pushed the button this many times:'),

          Text('$_counter', style: Theme.of(context).textTheme.headline4),

        ],

      ),

    ),

    floatingActionButton: FloatingActionButton(

      onPressed: _incrementCounter,

      tooltip: 'Increment',

      child: Icon(Icons.add),

    ),

  );

}


🧠 Understanding Widget Hierarchy

Widget

Purpose

Scaffold

Basic layout for app

AppBar

Top navigation bar

Center

Centers child widgets vertically/horizontally

Column

Arranges widgets vertically

Text

Displays static or dynamic text

FloatingActionButton

A round button for actions


🎯 Customizing Your App

Changing the Theme

In MaterialApp:

dart

 

theme: ThemeData(

  primarySwatch: Colors.green,

  fontFamily: 'Roboto',

),


Adding More Buttons

dart

 

Row(

  mainAxisAlignment: MainAxisAlignment.center,

  children: [

    ElevatedButton(

      onPressed: () => print('Reset!'),

      child: Text('Reset'),

    ),

    SizedBox(width: 10),

    ElevatedButton(

      onPressed: _incrementCounter,

      child: Text('Add'),

    )

  ],

)


🎨 Using Widgets Effectively

Flutter offers two key types of widgets:

Widget Type

Description

Example

StatelessWidget

Does not manage any state

Login logo, text heading

StatefulWidget

Changes dynamically with state

Counters, forms, toggles


🧱 Custom Widget Example

dart

 

class MyButton extends StatelessWidget {

  final String label;

  final VoidCallback onPressed;

 

  MyButton({required this.label, required this.onPressed});

 

  @override

  Widget build(BuildContext context) {

    return ElevatedButton(

      onPressed: onPressed,

      child: Text(label),

    );

  }

}

Use it like:

dart

 

MyButton(label: 'Click Me', onPressed: () => print('Clicked'))


🧪 Testing the App

Run the app using:

bash

 

flutter run

Use the hot reload feature (r) to see changes instantly.


🧠 Tips for Beginner App Development

  • Keep widget trees clean and well-indented
  • Split complex widgets into separate Dart files
  • Use const constructors where possible for performance
  • Don’t forget to handle null safety (?, !, default values)

🔄 Adding Navigation (Preview)

You can use routes to move between pages:

dart

 

Navigator.push(

  context,

  MaterialPageRoute(builder: (context) => SecondPage()),

);

We’ll cover this in Chapter 4: Layouts and Navigation in Flutter.


Summary

You’ve now successfully:

  • Created your first Flutter app
  • Understood the widget tree and how UI is structured
  • Worked with both StatelessWidget and StatefulWidget
  • Updated the UI based on user interaction
  • Customized the app’s layout and theme


This hands-on experience lays the groundwork for building complex, real-world apps in Flutter.

Back

FAQs


❓1. What is Flutter and why should I use it?

Answer:
Flutter is an open-source UI toolkit by Google that enables you to build natively compiled apps for mobile, web, and desktop from a single codebase. It’s fast, efficient, and perfect for building beautiful, responsive UIs with a single programming language—Dart.

❓2. Do I need to know Dart before learning Flutter?

Answer:
Not necessarily. Dart is easy to learn, especially if you’re familiar with JavaScript, Java, or C#. Most Flutter tutorials introduce Dart basics along the way, making it beginner-friendly.

❓3. Can I build both Android and iOS apps with Flutter?

Answer:
Yes! Flutter allows you to develop apps for Android and iOS from a single codebase. You can also compile apps for web, Windows, macOS, and Linux using the same project.

❓4. What are the system requirements to run Flutter?

Answer:
You’ll need a modern operating system like Windows 10+, macOS, or Linux, along with tools like Git, an IDE (VS Code or Android Studio), and device emulators or simulators for testing.

❓5. What is "hot reload" in Flutter?

Answer:
Hot reload is a Flutter feature that allows you to instantly see code changes in your running app without restarting the entire application. It boosts productivity and speeds up the development process.

❓6. How do I install Flutter on my computer?

Answer:
You can download the Flutter SDK from flutter.dev, extract it to a folder, add it to your system PATH, and run flutter doctor to check for setup issues. IDE plugins are also available for Android Studio and VS Code.

❓7. Is Flutter good for web development?

Answer:
Yes, Flutter supports web development, though it’s still evolving compared to mobile. It’s ideal for building highly interactive web apps or PWAs with consistent UI and shared code.

❓8. What are widgets in Flutter?

Answer:
Widgets are the building blocks of a Flutter app. Everything you see on screen—text, buttons, layout elements, animations—is a widget that can be customized or nested inside other widgets.

❓9. How does Flutter compare to React Native?

Answer:
Both are popular cross-platform frameworks, but Flutter offers better performance due to its native rendering engine and avoids using platform views. React Native uses JavaScript and relies more on native components.

❓10. Where can I find good Flutter tutorials and resources?

Answer:
Start with the official Flutter documentation, Flutter YouTube channel, freeCodeCamp, and community blogs on Medium or Dev.to. You can also explore interactive learning on Flutter Apprentice.