flutter - 如何在 Flutter 的对话框中访问 Provider 提供者

标签 flutter flutter-provider inherited-widget

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

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

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

相关文章:

flutter - 如何在 Flutter 移动应用程序中将 Azure AD 用户登录到 Firebase?

flutter - 数据加载时如何等待或重建Consumer

flutter - ChangeNotifierProvider 中 Consumer/Provider.of 的区别

performance - 为什么findAncestorWidgetOfExactType为O(N)而DependOnInheritedWidgetOfExactType为O(1)

flutter - 如何让应用程序保持清醒?

android - 如何在 Flutter 中为文本创建气泡? (WhatsApp 用户界面)

flutter - "setState() or markNeedsBuild() called during build"尝试在消费者小部件(提供程序包)内的导航器中推送替换时出错

dart - InheritedWidget 困惑

dart - 正确 Flutter 小部件序列以在应用加载时提取数据

android - Flutter - 在应用程序中显示 android 主屏幕小部件