I have a Parent
widget, which holds some state, a counter in this case.
This state is passed on to a Child
widget using its constructor.
Now, how I understand it, the Child
should get re-built every-time Parent
's state changes, since it's inside the build()
function of Parent
, and build()
gets called every-time the state changes.
This concept lead me to believe that the INIT STATE!
message would be printed every time the counter changes. But it is not the case!
I essentially want a "hook" that gets fired only once, whenever the Child
's constructor arguments (message
) change.
Can someone please explain why this is the case, and what is the right way to have the aforementioned "hook"?
class Child extends StatefulWidget { final String message; const Child(this.message, {Key key}) : super(key: key); @override _ChildState createState() => _ChildState(); } class _ChildState extends State<Child> { @override void initState() { print("INIT STATE!"); super.initState(); } @override Widget build(BuildContext context) { return Center( child: Text(widget.message), ); } } class Parent extends StatefulWidget { @override _ParentState createState() => _ParentState(); } class _ParentState extends State<Parent> { int _counter = 0; @override void initState() { Timer.periodic(Duration(seconds: 1), (_) { if (mounted) { setState(() { _counter += 1; }); } }); super.initState(); } @override Widget build(BuildContext context) { return Child(_counter.toString()); } }
In this example, the initState() is called only once. This means the results of clicking + or – icons won't get displayed on the screen. However, this clicking will always execute the setState() and pass the new value to the widget tree.
To call a function of a parent, you can use the callback pattern. In this example, a function on the color selected is passed to the child. The child calls the function when a button is pressed: import 'package:flutter/material.
The solution is to pass a new Key to WidgetB every time we need it to be rebuilt: WidgetA will see that WidgetB has changed and will rebuild it when setState is called. In other words, whenever a stateful widget's Key property changes, calling setState on its parent will force a rebuild of the stateful widget.
Ok, looks like this was clearly mentioned in the State class' docs.
The correct way to do this is to override the didUpdateWidget
method in the State
subclass.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With