Explanation of why Flutter initState is called twice
In Flutter, the initState()
method is called when the Stateful Widget is inserted into the widget tree and it is only called once during the lifecycle of the widget. However, there are cases where it may appear that initState()
is being called twice, which can be confusing.
One common reason for initState()
being called twice is when the widget is being rebuilt. When the parent widget rebuilds, for example due to a state change, it triggers the rebuilding of its children widgets as well. This can cause the Stateful Widgets to be recreated and hence initState()
is called again.
To illustrate this behavior, let’s consider a simple counter example using Flutter:
<!-- language: lang-dart -->
import 'package:flutter/material.dart';
class CounterWidget extends StatefulWidget {
@override
_CounterWidgetState createState() => _CounterWidgetState();
}
class _CounterWidgetState extends State<CounterWidget> {
int counter = 0;
@override
void initState() {
super.initState();
print('initState() called');
}
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Counter: $counter'),
RaisedButton(
child: Text('Increment'),
onPressed: () {
setState(() {
counter++;
});
},
),
],
);
}
}
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter initState'),
),
body: Center(
child: CounterWidget(),
),
),
);
}
}
The above code defines a CounterWidget that displays a counter value and an increment button. When the button is pressed, the counter value is incremented using the setState()
method, which triggers a rebuild of the widget tree.
When running the code, you will notice that initState()
is called only once initially when the widget is inserted into the widget tree. However, if you tap the increment button, initState()
is not called again because the widget is not being recreated. Instead, the build()
method is called again with the updated counter value, resulting in the counter being displayed on the screen.
To summarize, initState()
is called only once when the Stateful Widget is initially inserted into the widget tree. If it appears to be called twice, it is likely due to the widget being rebuilt. Understanding the widget lifecycle and how state changes trigger rebuilds is crucial for working with Flutter and can help in avoiding confusion around initState()
or any other lifecycle methods being called multiple times.