Reputation: 1218
in my app I have a navigation drawer and the body is updated according to the tile pressed in the drawer. The body is the same for each class, it is a statefulwidget and returns a listview. For each instance of this class (and so for every tile) I need to call the initState method. I notice that it is called just on the first instance of the first tile, then it call just the build method. How can I run a piece of code the first time for every instance?
Synthesis: in the app there's a drawer with many tile, each tile is associated with an instance of a class that is the body of the app. But the initState is called just on th first instance.
Here's an example:
class FirstPage extends StatefulWidget {
@override
_FirstPage createState() => new _FirstPage();
}
class _FirstPage extends State<FirstPage> {
@override
void initState() {
super.initState();
print("debug");
}
@override
Widget build(BuildContext context) {
print('hi');
return ListView(children: <Widget>[Text('text')],
);
}
}
If I instantiate this class the first time it prints: debug and hi. The second time I instantiate this it prints just: hi
Upvotes: 1
Views: 118
Reputation: 277467
You can't. The whole point of initState
is to be called once on state initialization.
You may want to look at other life cycles. Such as
Upvotes: 1