Cannot get widget's property in build function

71 Views Asked by At

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?

1

There are 1 best solutions below

5
On

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,

flutter pub add provider

model.dart

class ModelState extends ChangeNotifier{
final List<String> imagePaths;

const ModelState({this.imagePaths = []}):super();

void updatePathsToList(String input){
imagePaths = input.split(",");
notifyListeners();
}

}

accessing functions of provider from parent function to input the path

initState((){
context.read<ModelProvider>().updatePathsToList(_path)
})

Using in UI (watching changes)

context.watch<ModelProvider>().imagePaths

The above approach should help, go through a basic provider video to understand how this works. Hope this helps.