Stateless and Stateful Widgets: Understanding the Building Blocks
In Flutter, everything is a widget. Widgets are the fundamental building blocks of your UI. They define how your app looks and interacts with the user.
-
Stateless Widgets:
These widgets are immutable. They do not store any state that changes over time.
Examples include
Text
,Icon
, andImage
.class MyStatelessWidget extends StatelessWidget { @override Widget build(BuildContext context) { return Text('Hello, Flutter!'); } }
-
Stateful Widgets:
These widgets maintain state that can change during the widget's lifetime.
Examples include
Checkbox
,Slider
, andTextField
.class MyStatefulWidget extends StatefulWidget { @override _MyStatefulWidgetState createState() => _MyStatefulWidgetState(); } class _MyStatefulWidgetState extends State<MyStatefulWidget> { int counter = 0; @override Widget build(BuildContext context) { return Column( children: [ Text('Counter: \$counter'), ElevatedButton( onPressed: () { setState(() { counter++; }); }, child: Text('Increment'), ), ], ); } }
Layouts and Containers: Creating Responsive UIs
Flutter’s layout system is highly flexible. Widgets like Row
, Column
,
Stack
, and Container
help you create complex UIs with ease.
- Container: A versatile widget for padding, margins, alignment, and decoration.
- Row and Column: Arrange widgets horizontally or vertically.
- Stack: Place widgets on top of each other for layered designs.
Widget build(BuildContext context) {
return Center(
child: Container(
padding: EdgeInsets.all(16),
color: Colors.blueAccent,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Hello, Flutter!', style: TextStyle(color: Colors.white)),
SizedBox(height: 10),
Icon(Icons.flutter_dash, color: Colors.white, size: 48),
],
),
),
);
}
Styling and Theming: Consistent Designs Across Your App
Flutter allows you to define a global theme that applies consistent colors, typography, and styles
across your app using the ThemeData
class.
MaterialApp(
theme: ThemeData(
primarySwatch: Colors.indigo,
textTheme: TextTheme(
bodyMedium: TextStyle(fontSize: 16, color: Colors.black87),
),
),
home: MyHomePage(),
);
You can also style individual widgets with properties like color
,
padding
, margin
, and decoration
.
Combining layout and styling allows you to create responsive and visually appealing interfaces.
0 Comments