Widgets are the basic building blocks of Flutter apps. They are Flutter objects that you are able to place onto the screen.
Many programming frameworks have similar concepts such as ‘components’ - in Flutter they are called ‘widgets’.
There are already a bunch of ready-made widgets that come with Flutter such as Text
and Image
. If you can use combine the ready made widgets to create bigger and better widgets.
The following is a very basic widget.
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return Text("My first widget!");
}
}
The important part of this code is that the class MyWidget
has a build
function which returns the Text
widget, and because MyWidget
's build
function returns a widget, MyWidget
is also another widget.
<aside>
💡 const MyWidget({super.key});
is a necessary constructor for the function to work. It is forced by the Flutter framework.
</aside>
<aside>
💡 The build
function is overriding thebuild
function of the StatelessWidget class.
</aside>
<aside> 💡 The widget right now are stateless. This means they cannot remember information (i.e state). Later we will show stateful widgets.
</aside>