In Flutter, Widgets are the basic building blocks for constructing the user interface of an app. Every view in Flutter is a Widget. There are two main types of Widgets in Flutter:
Stateless Widgets
Stateless Widgets are widgets that do not have any state and do not change after being created. When the app's state changes, Stateless Widgets get redrawn with the new values but do not retain any state.
Stateful Widgets
Stateful Widgets are widgets that have state and can change during runtime. When the state changes, Stateful Widgets automatically get redrawn to reflect the new changes.
Flutter provides a variety of built-in Widgets such as Text, Image, RaisedButton, Container
and many more to construct the user interface. Additionally, you can create custom Widgets to suit specific app requirements.
Using Widgets in Flutter
To use Widgets in Flutter, you simply create the Widgets and arrange them in the app's Widget tree. Flutter uses a Widget tree structure to build the user interface. Each Widget can contain child Widgets, forming a hierarchical structure.
For example, to create a simple app with a button and some text, you can use Widgets like this:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Widgets'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
onPressed: () {
// Xử lý khi nút được nhấn
},
child: Text('Nhấn vào đây'),
),
Text('Chào mừng đến với Flutter Widgets'),
],
),
),
),
);
}
}
In the example above, we use MaterialApp, Scaffold, Column, RaisedButton, Text Widgets
to build a simple interface
. You can change the Widgets and the Widget tree structure to create more complex and dynamic user interfaces for your app.
Conclusion
Widgets are the foundation of the user interface in Flutter. By using built-in Widgets and creating custom Widgets, you can build diverse and engaging apps in Flutter.