Sub topic 2
Flutter Widgets: StatelessWidget and StatefulWidget
This chapter assumes you know Dart classes, constructors, final fields, named parameters, and null safety. You should also have a Flutter app that runs.
Writing a StatelessWidget
A StatelessWidget keeps no changing data. Its fields are set once through the constructor, and its build method returns the same UI for the same inputs.
import 'package:flutter/material.dart';
class Greeting extends StatelessWidget {
const Greeting({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) {
return Text('Hello, $name');
}
}The const constructor lets Flutter reuse the widget instance when a parent rebuilds, which saves work.
Writing a StatefulWidget and its State
A StatefulWidget splits into two classes. The widget itself is immutable configuration. The State object holds the data that must survive rebuilds.
import 'package:flutter/material.dart';
class Counter extends StatefulWidget {
const Counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: _increment,
child: Text('Count: $_count'),
);
}
}Changing the UI with setState
Calling setState runs the function you pass, then schedules a new build. If you change _count without setState, the value changes but the screen does not update.
Choosing between stateless and stateful
Start with a StatelessWidget. Use a StatefulWidget only when the widget itself must remember a value that changes over time.
| UI element | Widget type |
|---|---|
| Fixed label or icon | StatelessWidget |
| Button that counts taps | StatefulWidget |
| Text field that holds typed input | StatefulWidget |
| Card that displays data passed in | StatelessWidget |
Where the state belongs also matters. A child that only displays a value should receive it from a parent, so the child can stay stateless.
Exercise
A label shows a title that never changes. Should it be a StatelessWidget or a StatefulWidget, and why?
Show answer
StatelessWidget. Nothing in it changes over time, so it needs no State object and no setState call.