Understanding Flutter’s setState() method with async
The setState()
method in Flutter is used to update the state of a widget. It ensures that the widget is rebuilt with the updated state and reflects the changes visually. When working with asynchronous operations, such as fetching data from an API, you may need to use async
and await
along with setState()
to properly handle the updates in the widget.
Example:
Let’s consider a simple example where we have a counter displayed on the screen. The counter starts at 0 and increments by 1 every 1 second.
import 'package:flutter/material.dart';
class MyCounter extends StatefulWidget {
@override
_MyCounterState createState() => _MyCounterState();
}
class _MyCounterState extends State<MyCounter> {
int counter = 0;
@override
void initState() {
super.initState();
startCounter();
}
void startCounter() async {
while (true) {
await Future.delayed(Duration(seconds: 1));
setState(() {
counter++;
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Async Counter'),
),
body: Center(
child: Text(
'Counter: $counter',
style: TextStyle(fontSize: 24),
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyCounter(),
);
}
}
In this example, we have a stateful widget called MyCounter
which maintains the counter
variable. The initState()
method is overridden to start the counter using startCounter()
method.
The startCounter()
method is declared as async
since we need to use await
to delay the execution by 1 second. Inside the loop, we increment the counter and call setState()
to reflect the updated value on the screen.
The build()
method of the widget displays the counter using the Text()
widget. Whenever setState()
is called, Flutter rebuilds the widget and updates the UI with the new value of the counter.
By using setState()
along with async
and await
, we can ensure that Flutter properly updates the widget’s state using the updated value after each delay.