Widget Essentials
Widget Essentials
Section titled “Widget Essentials”In Flutter, Everything is a Widget. From the layout model to the text on the screen, even the application itself is a widget.
The Widget Lifecycle
Section titled “The Widget Lifecycle”Understanding the lifecycle of a widget is critical for managing memory and specialized behavior (like controllers).
Stateless Widgets
Section titled “Stateless Widgets”Use these for static content. They are cheap to create.
class MyIcon extends StatelessWidget { const MyIcon({super.key}); // Use const constructors!
@override Widget build(BuildContext context) { return const Icon(Icons.star, color: Colors.yellow); }}[!TIP] Performance Tip: Always use
constconstructors where possible. This tells Flutter that the widget will not change, allowing it to reuse the element during rebuilds.
Stateful Widgets
Section titled “Stateful Widgets”Use these when you need to maintain state (user input, animations, scrolling position).
- createState(): Creates the mutable state object.
- initState(): Called once. Initialize controllers/listeners here.
- build(): Called every time
setStateis triggered. - dispose(): Called when the widget is removed. Clean up controllers here!
class MyPage extends StatefulWidget { const MyPage({super.key});
@override State<MyPage> createState() => _MyPageState();}
class _MyPageState extends State<MyPage> { late final TextEditingController _controller;
@override void initState() { super.initState(); _controller = TextEditingController(); }
@override void dispose() { _controller.dispose(); // Vital to prevent memory leaks! super.dispose(); }
@override Widget build(BuildContext context) { return TextField(controller: _controller); }}Material Design 3
Section titled “Material Design 3”Flutter 3 defaults to Material 3. You can customize the theme in your MaterialApp:
MaterialApp( theme: ThemeData( useMaterial3: true, colorSchemeSeed: Colors.blue, // Generates a full color palette ), home: const HomePage(),);Common Widgets Categories
Section titled “Common Widgets Categories”- Display: Text, Icon, Image.
- Input: TextField, Checkbox, Slider, InkWell (for taps).
- Layout: Row, Column, Stack, ListView.
- Async: FutureBuilder, StreamBuilder.