Understanding Flutter Widgets: The Basics
π± What is a Widget in Flutter?
In Flutter, everything is a widget—text, buttons, layouts, and even the app itself.
A widget is a building block of the UI.
There are two main types of widgets:
1. StatelessWidget
Immutable: cannot change once built
Used when the UI doesn’t depend on any dynamic data or state
dart
Copy code
class MyStatelessWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Text('Hello, Flutter!');
}
}
2. StatefulWidget
Mutable: can change over time (has state)
Used when the UI needs to update dynamically (e.g., counters, form inputs)
dart
Copy code
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int counter = 0;
void _increment() {
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Counter: $counter'),
ElevatedButton(
onPressed: _increment,
child: Text('Increment'),
),
],
);
}
}
π§© Widget Tree
Flutter builds UI as a tree of widgets (also called the widget tree). Widgets can be nested inside each other.
dart
Copy code
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('My App')),
body: Center(
child: Text('Hello, World!'),
),
),
);
Widget hierarchy (simplified):
scss
Copy code
MaterialApp
└── Scaffold
├── AppBar
└── Body → Center
└── Text
π ️ Common Flutter Widgets
Category Widget Description
Layout Row, Column Arrange children horizontally/vertically
Display Text, Image Show text or images
Input TextField, Form, Checkbox Accept user input
Buttons ElevatedButton, TextButton Trigger actions
Containers Container, Padding, Card Style and layout wrappers
Navigation Navigator, Drawer, BottomNavigationBar Handle app navigation
π Rebuilding & Performance
StatelessWidgets rebuild when their parent rebuilds
StatefulWidgets can rebuild when setState() is called
Flutter is optimized for performance using a widget rebuild mechanism
π‘ Tips for Beginners
Use Hot Reload for faster development
Break down large widgets into smaller components
Use const constructors when possible for performance
Learn the layout model: spacing, alignment, constraints
Would you like:
An illustrated guide or diagram of the widget tree?
A Flutter widget cheat sheet?
A beginner project tutorial?
Learn Flutter Training in Hyderabad
Read More
Setting Up Flutter on Windows/Mac/Linux
What is Flutter? An Introduction for Beginners
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment