I need pass provider (Model2
) from homepage
to Page2
so when user go back to homepage
(onWillPop
) I can make API call from provider (Model2
) and update homepage
.
But when I call _onPaidBackPress(context)
there is error:
Unhandled Exception: Error: Could not find the correct Provider above this Consumer Widget
StatefulWidget
in homepage:
@override
Widget build(BuildContext context) {
return ChangeNotifierProxyProvider<Model1, Model2>(
initialBuilder: (_) => Model2(),
builder: (_, model1, model2) => model2
..string = model1.string,
),
child: Consumer<Model2>(
builder: (context, model2, _) =>
...
await Navigator.push(
context,
new MaterialPageRoute(
builder: (BuildContext context) =>
new Page2(
context: context)));
In Page2:
class Page2 extends StatefulWidget {
final BuildContext context;
Page2({Key key, this.context}) : super(key: key);
@override
State createState() => new Page2State(context: context);
}
class Page2State extends State<Page2> {
final context;
ChatScreenState({Key key, this.context});
@override
Widget build(BuildContext context) {
return Consumer<Model1>(
builder: (context, model, _) {
return new WillPopScope(
onWillPop: () => model.isPaid ? _onPaidBackPress(context) : _onBackPressed(context),
Future<void> _onPaidBackPress(context) async {
final model2 = Provider.of<Model2>(context, listen: false);
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return
Provider.value(value: model2, child:
AlertDialog(
title: Text('Back'),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text('Go back'),
],
),
),
actions: <Widget>[
FlatButton(
child: Text('OK'),
onPressed: () async {
await model2.getData();
Navigator.of(context).pop();
},
),
],
),
);
},
);
}
Thanks for help!