Flutter — main.dart & Widgets
As a prerequisite, here you need to install Flutter on your machine, and you also need to create a new Flutter project.
You can simply create new project using the command ,
flutter create project_name
Then go to the created project,
Once you have created your project, you will see the “lib” folder where the “main.dart” file is located.
Most importantly, once you have created a project and developed the application, Flutter expects the “main.dart” file to exist.
Therefore, you should not delete or rename file name this “main.dart” file, it should remain. But you can update the content as you wish.
Let us see the functions and variables one by one in this main.dart file.
- main() — We know that any programming language has the main entry point. This means that this is where our program first gets programmatically executed. So in dart we also have this, main () function.
So what we need to write in the main() function
As I described above, this will execute at the very beginning, so we need to include what we need to show first.
So in Flutter, we treat these items as widgets.
Also, we develop the application with the help of these widgets. So, the goal of the main () function is to show those widgets to the user.
Flutter Widgets
Everything in a Flutter app is a widget in Flutter, from simple “text” to “buttons” to “screen layouts”. This widget arranges the hierarchies in order to be displayed on the screen.
Flutter Widget Tree
The widget tree is a structure that represents how our widgets are organized
Of course, widgets are not just building blocks, where we can write our business logics, ex: what to do when the button is pressed.
We can also identify them as independent components and nested components.
Simple example
import 'package:flutter/material.dart';void main() => runApp(MyApp());class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key);@override Widget build(BuildContext context) { return const MaterialApp( home: Text("Hello World Niluka"),
);
}
}
output: