Flutter First App Basic Code Structure Explained Tutorial with Example

Hello Guys, This tutorial is mainly for Flutter beginners but even if you are a Pro developer this could help you to understand some Flutter basics. In this tutorial we would modify the flutter first app code into a simple one and explained step by step each line of code. We would make sure that you understand the whole code because it is the base of every single Flutter app. So let’s get started :). See the below code i have posted my whole main.dart file code here below first then i am going to start explaining them.  Just copy and paste the below code in your own main.dart file to see the first time effect.

Source code for main.dart file:

Explanation of above code in simplest form:

1. Every time when we start our new flutter code there is one step compulsory to import the material.dart package in your application. This package contains some of Flutter basic widgets like Text, AppBar, runApp() etc. One more thing you should close each line with semi-column like i did here.

2. On next step we would call our Main widget class using void main function. Void main function is the main function defined in Flutter, which executes every single time when a application reloads. Here we can use its runApp() function which tells the compiler to execute the pass class. Just like here we have pass our MyApp class in it. So every time when application loads it would call the MyApp class. This syntax supports one line function execution. runApp() function takes widget pass in it and draw the widget on the mobile screen.

You can also call the runApp() function using by passing it completely in main function like below code. Both syntax is correct bat it depends on your requirement.

3. Creating Class MyApp extends with StatelessWidget. Every single widget in Flutter must extends Stateless Widget or State full widget.

4. StatelessWidget and StatefullWidget has its own build method which flutter calls every time when we want to draw something on screen. build method always returns a new Widget which app should draw on screen. Here context is a type of object type of BuildContext. You don’t need to worry about its value. Flutter will automatically assign value to it.

5. On next step we would return the base widget using MaterialApp. It supports an argument so we give it home. Here we would create the base widget named as Scaffold. Scaffold is a inbuilt widget in material.dart class. This class would give you a proper basic UI which looks like a application page.

  1. appBar : We would pass the AppBar class here to make simple sky blue color Appbar.
  2. body : In body section we would pass the widget which we want to show inside the application. Here we are showing the only the Text widget.

Screenshot of App:

Flutter First App Basic Code Structure Explained

Leave a Reply

Your email address will not be published. Required fields are marked *