Setstate & Initstate
Setstate & Initstate
In Flutter, `setState` and `initState` are commonly used methods in stateful widgets, playing crucial roles in
managing state and initializing the widget, respectively. Here's a breakdown of each:
initState:
initState: is a lifecycle method that is called when the stateful widget is inserted into the widget tree.
This method is used to perform any initialization that needs to occur before the widget is built.
- It is called once when the stateful widget is created.
- It is often used to initialize data or set up listeners.
- You must call `super.initState()` to ensure that the parent class's initialization code runs.
Example:
class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
@override
Widget build(BuildContext context) {
return Container(
// Widget build code here
);
}
}
setState:
`setState` is a method that you call whenever you want to update the state of the widget and reflect those
changes in the UI. It tells the framework that the state has changed and the widget needs to be rebuilt.
Example:
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Counter App'),
),
body: Center(
child: Text(
'Counter: $_counter',
style: TextStyle(fontSize: 24),
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
child: Icon(Icons.add),
),
);
}
}
Flutter Page 1
you can modify the state variables and the framework will call the `build` method to update the UI.
Flutter Page 2