我需要将 provider( Model2
) 传递给homepage
to,Page2
因此当用户返回homepage
( onWillPop
) 时,我可以从 provider() 进行 API 调用Model2
并更新homepage
。
但是当我打电话时_onPaidBackPress(context)
出现错误:
未处理的异常:错误:在此消费者小部件上方找不到正确的提供者
StatefulWidget
在主页:
@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)));
在第 2 页中:
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();
},
),
],
),
);
},
);
}
感谢帮助!