在应用主页上我设置了 Model2
这使得 API 调用数据。然后用户可以导航到其他页面 (Navigator.push
)。但我想从 Model2
进行 API 调用当用户按下 (_onBackPress()
) 时,可以刷新主页上的数据。
问题是 Model2 没有为所有用户初始化。但是如果我调用 final model2 = Provider.of<Model2>(context, listen: false);
对于未初始化 Model2 的用户,这将给出错误。
我如何只能在有条件的情况下调用提供者?例如:if(user == paid)
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, _) =>
...
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute(context: context)),
在第 2 页中:
Future<void> _onBackPress(context) async {
// if(user == paid)
final model2 = Provider.of<Model2>(context, listen: false);
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return
// if(user == paid)
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 {
// if(user == paid)
await model2.getData();
Navigator.of(context).pop();
},
),
],
),
);
},
);
}
替代方法(可能更简单):如何在
Navigator.of(context).pop();
上的上一页(主页)上调用提供者?TLDR:什么是调用 API 的最佳解决方案,以便在用户返回上一页时刷新数据(但仅适用于某些用户)?
最佳答案
您可以将您的第二页界面构建器包装在 WillPopScope
中。小部件,然后将您要调用的任何方法传递给 onWillPop
WillPopScope
的回调小部件。这样,您可以在用户按下后退按钮时进行 API 调用。查找有关 WillPopScope
的更多信息this WillPopScope Flutter dev documentation article 上的小部件.
关于flutter - 如何在有条件的情况下调用提供者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57594576/