flutter - 如何在 Flutter 的 Dialogs 中访问 Provider 提供者
问题描述
Provider 包使用InheritedWidget
. 当我想在对话框中访问提供者时,这是一个问题。如果我使用加载对话框
showDialog(... builder: (context) => MyDialog);
我无法访问任何内容,InheritedWidget
因为我的对话框不是主小部件树的一部分。这也意味着我无法访问我的 Provider 提供商,对吗?
我的问题是:如果它不是主应用程序小部件树的一部分,我如何在对话框中访问我的提供程序?
final firebaseAuth = Provider.of<FirebaseAuth>(context);
我在使用BLoCs
. 如果我尝试在对话框中通过 检索它们InheritedWidget
,它们会失败。我已经通过BLoC
在构造函数中传递来解决这个问题,但这似乎违背了InheritedWidgets
.
解决方案
您可以使用 BlocProvider.value,而不是在构造函数中传递 BLoC。
https://pub.dev/documentation/flutter_bloc/latest/flutter_bloc/BlocProvider/BlocProvider.value.html
这将允许您将现有的 BLoC 实例提供给新路由(对话框)。你仍然可以获得所有的好处InheritedWidget
// Get the BLoC using the provider
MyBloc myBloc = BlocProvider.of<MyBloc>(context);
showDialog(
context: context,
builder: (BuildContext context) {
Widget dialog = SimpleDialog(
children: <Widget>[
... // Now you can call BlocProvider.of<MyBloc>(context); and it will work
],
);
// Provide the existing BLoC instance to the new route (the dialog)
return BlocProvider<MyBloc>.value(
value: myBloc, //
child: dialog,
);
},
);
.value() 也存在于 ChangeNotifierProvider、ListenableProvider 等。 https://pub.dev/documentation/provider/latest/provider/ChangeNotifierProvider/ChangeNotifierProvider.value.html
推荐阅读
- arduino - 如何更正错误 - 此范围内未定义“A2”?
- c# - 类作为参数
- python - 在 Django 视图中将对象的参数设置为其默认值
- angular - ag-grid @version v17.1.1 无法读取未定义的属性“创建”
- powershell - 使用 PowerShell 将大型 csv 上传到表存储(非顺序)
- sql - 如何从sql server的一个表中检索图像并将其保存到另一个表
- javascript - 在提交表单时填写优惠券代码,然后发送表单
- spring - 单独配置分层 Spring 应用程序上下文
- python - 找到小于 X 的立即数
- python - 更改 plt.plot() 中的 x 轴值