Widgets in Flutter
What is Flutter Widgets?
In Flutter, everything on the screen is a widget. Flutter widgets are the UI elements that you see on the screen e.g. button, text, image, list, etc. Widgets can be either stateful or stateless.
Types of Widgets in Flutter
Flutter widgets are broadly categorized into:
- Stateless Widget
- Stateful Widget
Stateless Widget
Stateless widgets are immutable. Once you define their properties, they remain constant and don’t change. They are the go-to choice for displaying static content like text, images, or icons.
Note: You can use stl shortcut to create a stateless widget in VS Code.
Example of a Stateless Widget:
class MyStatelessWidget extends StatelessWidget {
final String text;
MyStatelessWidget({required this.text});
@override
Widget build(BuildContext context) {
return Text(text);
}
}
Stateful Widget
Stateful widgets are dynamic and can change during their lifecycle, usually in response to user interactions or real-time data updates. They are essential for content that evolves over time, such as a shopping cart’s contents.
Note: You can use stf shortcut to create a stateful widget in VS Code.
Example of a Stateful Widget:
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int counter = 0;
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
setState(() {
counter++;
});
},
child: Text('You have pressed the button $counter times.'),
);
}
}
Stateless Vs Stateful Widgets
Stateless Widgets | Stateful Widgets | |
---|---|---|
Properties | Stateless widgets remain constant and don’t change | Stateful widgets can change their appearance based on events or data. |
Use Case | For static content (e.g., buttons, icons) | For dynamic content (e.g., user interactions) |
State | No internal state | Maintains internal state that can be updated |
Rebuild | Entire widget tree rebuilt on state changes | Rebuilds only the widget affected by state change |
Most Used Flutter Widgets
- Text: It is used to display text on the screen.
- Container: It is used to display a rectangular box on the screen.
- Row: It is used to display widgets in a horizontal manner.
- Column: It is used to display widgets in a vertical manner.
- Stack: It is used to display widgets on top of each other.
Note: You can use Container widget to add padding, margin, border, background color, etc. to other widgets.