DEV Community

Cover image for Flutter Basics for Beginners: Understanding main(), runApp(), and Widgets
Flutter Sensei
Flutter Sensei

Posted on • Originally published at fluttersensei.com

Flutter Basics for Beginners: Understanding main(), runApp(), and Widgets

Have you ever had a brilliant idea for a mobile app, only to get stuck wondering where to begin?

You check the requirements and realize you need to learn Swift for iOS apps, Kotlin for Android apps, and maybe web development languages too.

It feels like trying to learn three different instruments at the exact same time just to play one song.

Fortunately, there is a much easier way. Welcome to Flutter—the framework that allows you to build beautiful, fast apps for any device using just a single codebase.

Whether you are a complete beginner who has never written a line of code, or a web developer looking to jump into mobile, this guide is your perfect starting point.

We are going to break down the core fundamentals of Flutter using simple English, practical examples, and clear explanations. Plus, we will look at how cutting-edge Agentic AI is completely changing how we learn and write code today.

Let’s dive in!

1. What is Flutter? (And Why Everyone Loves It)

When people search Google for "How to build an app for both Android and iOS," the number one answer they find is Flutter.

But what exactly is it?

Flutter is a free, open-source UI (User Interface) software development kit (SDK) created by Google.

In plain English, it is a massive toolkit filled with pre-made buttons, text styles, animations, and design structures that help you build fully functional applications for mobile, web, desktop, and embedded devices from a single codebase.

The Magic of "Write Once, Run Anywhere"

Before frameworks like Flutter came along, companies had to hire two separate teams: one to build the iPhone version of the app and another to build the Android version.

This was expensive, time-consuming, and led to apps looking and feeling completely different on different phones.

With Flutter, you write your code once in a programming language called Dart (also created by Google), and Flutter compiles it into native machine code for both iOS and Android.

Why developers choose Flutter:

  • Fast Development (Hot Reload): Imagine making a change to your app's design, clicking save, and seeing it update on your phone screen in less than a second without restarting the app. That is called Hot Reload, and it feels like magic.
  • Beautiful Visuals: Flutter doesn't rely on the phone's default system buttons. It controls every single pixel on the screen, meaning your app will look exactly the same on an old Android phone as it does on the newest iPhone.
  • Great Performance: Because Flutter compiles directly to native code, your animations, scrolling, and transitions will feel incredibly smooth.

2. Setting Up the Engine: Understanding main() and runApp()

Every great story has a beginning, and every Flutter app starts in the exact same place. When you open a fresh Flutter project, you will see a file called main.dart.

Inside that file, two tiny pieces of code do all the heavy lifting to kickstart your application: main() and runApp().

Let’s look at a basic example:

void main() {
  runApp(const MyApp());
}
Enter fullscreen mode Exit fullscreen mode

This looks incredibly simple, but there is a lot of power hidden inside these few words. Let's break them down.

What is main()?

The main() function is the entry point of your application. Think of it as the front door of your house or the "Start" button on a video game console.

When the phone loads your app, the very first thing it does is look for the word main(). If it doesn't find it, the app won't run.

The void keyword just means that this function does its job without returning any data back to the system. It simply triggers the action.

What is runApp()?

If main() is the hand that turns the key in the ignition, runApp() is the engine starting up.

The runApp() function is a core part of Flutter.

It takes whatever widget you give it (in the case above, a widget called MyApp) and stretches it to cover the entire screen of the device. It tells Flutter: "Hey, grab this design, put it on the screen, and make it interactive for the user!"

Without runApp(), your code would execute in the background, but the user would just be looking at a blank, black screen.


3. What is a Widget? (The Building Blocks of Everything)

If you remember only one rule from this guide, make it this one: In Flutter, everything is a widget.

To understand Flutter, forget about complex coding jargon for a moment and imagine playing with LEGO blocks.

If you want to build a LEGO castle, you don't mold plastic from scratch; you take different blocks—some square, some rectangular, some red, some blue—and snap them together.

Flutter works exactly the same way. Every single thing you see on the screen is a block called a Widget.

  • A piece of text? That’s a Text widget.
  • An image? That’s an Image widget.
  • A button you can tap? That’s an ElevatedButton widget.
  • The space padding around an object? That’s a Padding widget.
  • An invisible row or column layout holding other items? Yes, those are widgets too (Row and Column).

The Widget Tree

Widgets don't just sit next to each other randomly; they nest inside one another to create a hierarchy known as the Widget Tree.

For example, if you want to display a profile card, your widget tree might look like this:

  • Container (The background card layout)
  • Row (Aligning items horizontally)
  • Image (The user’s profile picture)
  • Column (Aligning text vertically next to the picture)
  • Text ("Hello, User!")
  • Text ("Welcome back to your app.")

By combining simple building blocks, you can create incredibly intricate, beautiful, and complex mobile layouts.

4. The Big Debate: Stateless vs. Stateful Widgets

As you search Google for Flutter tutorials, you will constantly see two terms pop up: StatelessWidget and StatefulWidget.

Understanding the difference between these two is the ultimate "Aha!" moment for every beginner Flutter developer.

To understand them, we first need to define what State means. In app development, "State" is simply the data or information that your app cares about at a specific point in time.

It’s the current score in a game, the text typed into a login box, or whether a heart icon is clicked (red) or unclicked (grey).

Let’s break down the two types of widgets based on this concept.

A. Stateless Widgets (The Unchanging Designs)

A StatelessWidget is a widget that cannot change its look or data while the app is running.

Once it is drawn on the screen, it stays exactly the same until the user leaves the page. It is static.

Think of a billboard on the side of the road. Passing cars can look at it, but the text and image on the billboard won't change based on who is looking at it.

Real-world examples of a Stateless Widget:

  • A company logo at the top of a screen.
  • An informational paragraph explaining how to use the app.
  • An icon displaying a static house image for the "Home" page.

Here is what a complete, runnable Stateless Widget looks like in code:

import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(home: Scaffold(body: WelcomeText())));
}

class WelcomeText extends StatelessWidget {
  const WelcomeText({super.key});

  @override
  Widget build(BuildContext context) {
    return const Text(
      'Welcome to Flutter!',
      style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

B. Stateful Widgets (The Dynamic Apps)

A StatefulWidget is the exact opposite. It is dynamic and can change its appearance in real-time based on user interaction or data updates. When the "State" changes, the widget automatically redraws itself to reflect the new information.

Think of a digital scoreboard at a basketball game. Every time a player scores, someone presses a button, the data updates, and the screen changes immediately.

Real-world examples of a Stateful Widget:

  • A counter button that tracks how many glasses of water you drank today.
  • A checkbox that flips between checked and unchecked when tapped.
  • A shopping cart page that calculates a new total price when items are added or removed.

Here is a practical, runnable code example of an interactive counter built with a Stateful Widget:

import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      home: Scaffold(body: Center(child: WaterCounter())),
    ),
  );
}

class WaterCounter extends StatefulWidget {
  const WaterCounter({super.key});

  @override
  State<WaterCounter> createState() => _WaterCounterState();
}

class _WaterCounterState extends State<WaterCounter> {
  int _glasses = 0; // This is our "State" data

  void _incrementGlasses() {
    setState(() {
      // setState tells Flutter to redraw the screen with the new data
      _glasses++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          'Glasses of water today: $_glasses',
          style: const TextStyle(fontSize: 20),
        ),
        const SizedBox(height: 20),
        ElevatedButton(
          onPressed: _incrementGlasses,
          child: const Text('Drink a Glass of Water'),
        ),
      ],
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Did you notice the setState() function inside the code above? That is the secret sauce of stateful widgets.

When you wrap a variable change inside setState(), Flutter instantly clears the old design and draws the new screen with the updated numbers.


5. Supercharging Your Learning with Agentic AI

Now that you know the basics of Flutter widgets and how apps start up, you might feel a little overwhelmed by how much code there is to remember.

Ten years ago, you had to read massive textbooks or search forums for hours to debug a single missing semicolon.

Today, we live in the era of Agentic AI, and it is changing the landscape of software engineering education.

What is Agentic AI?

You are probably already familiar with conversational AI tools where you type a question, and it gives you a short response.

Agentic AI goes entirely beyond that. Instead of acting like a basic dictionary, an "AI Agent" acts like a proactive, autonomous coding assistant and personalized tutor.

It doesn’t just answer questions; it can think through complex problems, generate full application structures, anticipate errors before you make them, write automated tests, and walk you through step-by-step solutions customized precisely to your individual learning pace.

How Agentic AI Powers Flutter Development

When you pair Flutter with Agentic AI, your development speed multiplies. Here is how it helps you:

  1. Instant Visual Layouts: You can describe an app layout in plain English ("Create a modern dark-mode profile page with a profile picture, follower count, and a toggle switch"), and your AI agent will generate the exact Flutter widget tree you need.
  2. Context-Aware Debugging: If your code crashes or your widget layout looks broken on an iPad screen, an AI agent can analyze your files, find the bug, explain why it happened, and fix it for you instantly.
  3. An On-Demand Private Tutor: If you don't understand the difference between Stateless and Stateful widgets, an AI agent can generate infinite custom examples, quiz you, and adapt its teaching style until everything clicks perfectly.

Learning Flutter is no longer about memorizing hundreds of functions; it's about learning how to think creatively and using AI agents to turn those ideas into real-world code faster than ever before.


Take the Next Step: Build Real Apps Today!

Reading about widgets is a fantastic start, but the absolute best way to learn app development is by actually opening an editor, writing code, and seeing your creations come to life on your own phone screen.

If you are ready to stop just reading and start building, we have created the ultimate roadmap for you.

Check out our comprehensive, beginner-friendly video course: Flutter Foundations: Build Real Apps with Agentic AI.

In this course, we skip the boring academic lectures and build real, production-ready mobile apps from scratch.

You will master Flutter's core principles while unlocking the power of cutting-edge AI development tools to code smarter, troubleshoot bugs effortlessly, and build apps at lightning speed.

The mobile app market is growing every single day. Stop waiting for the "perfect time" to start your coding journey.

Grab your laptop, boot up your first widget, and let's build something incredible together!

Top comments (0)