Stateful and Stateless Widgets in Flutter

Arslan Raza
1 min readJan 3, 2023

--

In Flutter, a “stateful” widget is a widget that has a mutable state, which means that its state can change during the lifetime of the widget. A “stateless” widget is a widget that does not have a mutable state and its state is determined entirely by its properties.

Here is an example of a stateful widget in Flutter:

class Counter extends StatefulWidget {
@override
_CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
int _count = 0;

void _increment() {
setState(() {
_count++;
});
}

@override
Widget build(BuildContext context) {
return Row(
children: [
Text('Count: $_count'),
RaisedButton(
onPressed: _increment,
child: Text('Increment'),
),
],
);
}
}

Here is an example of a stateless widget in Flutter:

class Welcome extends StatelessWidget {
final String name;

Welcome(this.name);

@override
Widget build(BuildContext context) {
return Text('Welcome, $name!');
}
}

In general, it is recommended to use stateless widgets wherever possible because they are easier to reason about and more performant. However, stateful widgets may be necessary in some cases, such as when you need to maintain a state across multiple widgets or make asynchronous changes to the widget’s state.

--

--

Arslan Raza
Arslan Raza

Written by Arslan Raza

Mobile Applicaiton Developer

No responses yet