I have created a Flutter page which has a bunch of inputs in it. I thought this is a mess, let's refactor it and created a new stateful widget for each input.
This is great except the data needs to be in the parent widget and I am having a hard time understanding how to pass the data back from the new child widgets to the parent.
I've found some hacky way where you pass in a function and whenever there is a change you pass the data to the parent through that function.. Works but now there's multiple variables, one in the child and one in the parent.
I've read about the bloc pattern and I'm not sure whether this is what i need. I just want a singleton style object that the main widget and its children can both read and the children update when there is new input.
Would someone explain whether the bloc pattern would help me with this or if there is another design pattern that will help me with this.
** EDIT
Thanks for the great answers guys. My new problem is related to the provider pattern/library.
I have created some state classes as follows (ive replaced content to try and keep it simple)
class State1 with ChangeNotifier{
String _s;
set s(String newS){
_s = newS;
notifyListeners();
}
}
and then I use a multiprovider to pass it (create the objects in the init)
child: MultiProvider(
providers: [
ChangeNotifierProvider(builder: (context) => state1),
],
child: Stack(
alignment: Alignment.center,
children: stackChildren,
),
Which is then accessed in the children widegets build method using
state1Var = Provider.of<State1>(context);
And all of this works fine..
My issue is when I get to using a navigation push I can no longer access the state.
onPressed: (() {
Navigator.push(
contextField,
MaterialPageRoute(builder: (context) => NewPage()),
);
}),
As i get this error
Could not find the correct Provider<State1> above this NewPage Widget...
I did manage to get it using this
Navigator.push(
context,
MaterialPageRoute(builder: (context) => Consumer(builder: (),child: NewPage(),)),
);
But when I popped the widget using navigator.pop() the state couldnt be used as it said it had been disposed.
Sorry if i've made this complicated. I had to remove a lot of code.