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
关于flutter - 如何在 Flutter 的对话框中访问 Provider 提供者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57968453/