首页 > 解决方案 > 如何在 Flutter 的 Dialogs 中访问 Provider 提供者

问题描述

Provider 包使用InheritedWidget. 当我想在对话框中访问提供者时,这是一个问题。如果我使用加载对话框

 showDialog(... builder: (context) => MyDialog);

我无法访问任何内容,InheritedWidget因为我的对话框不是主小部件树的一部分。这也意味着我无法访问我的 Provider 提供商,对吗?

我的问题是:如果它不是主应用程序小部件树的一部分,我如何在对话框中访问我的提供程序?

final firebaseAuth = Provider.of<FirebaseAuth>(context);

我在使用BLoCs. 如果我尝试在对话框中通过 检索它们InheritedWidget,它们会失败。我已经通过BLoC在构造函数中传递来解决这个问题,但这似乎违背了InheritedWidgets.

标签: flutterflutter-providerinherited-widget

解决方案


您可以使用 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

https://pub.dev/documentation/provider/latest/provider/ListenableProvider/ListenableProvider.value.html


推荐阅读