I have two statefulWidget: Parent and Child.
And I wanna pass params from parent to child in initState().
// Parent.dart
class _ParentState extends State {
Child _child = Child()
@override
void initState() {
super.initState()
_dealWithChild();
}
function _dealWithChild() {
await SomeFunction()
...
_child.paths = '';
}
}
And get the params in the child:
class Child extends StatefulWidget {
String? _paths;
String? get paths => _paths;
set paths(String? value) {
_paths = value;
}
}
class _ChildState extends State {
@override
Widget build(BuildContext context) {
var _imagePaths = [];
//The widget.paths always null!
if (widget.paths != null) {
_imagePaths = widget.paths!.split(',');
}
}
}
But I cannot get the params in Child's build function. And if I don't call the async SomeFunction() in Parent, it works fine.
The question is that I have to call the async function and I cannot add async keyword to initState.
So how can I solve thie correctly?
I'd suggest using state management solutions like provider or block, that way you can set a state variable outside the widget tree & update it in any lifecycle method as and when needed, once you update the value of that path variable, the listener will get notified in the child ui & update it right away, below code might help,
model.dart
accessing functions of provider from parent function to input the path
Using in UI (watching changes)
The above approach should help, go through a basic provider video to understand how this works. Hope this helps.