【问题标题】:Changes to Stream Provider after migrating to null safety version Provider 5.0.0迁移到空安全版本 Provider 5.0.0 后对 Stream Provider 的更改
【发布时间】:2021-09-13 08:18:07
【问题描述】:

我已迁移到 dart null 安全版本。迁移功能中的命令修复了大多数问题。但是,我有一个使用 Firebase 处理用户会话的流提供程序。迁移到 Provider 版本 5.0.0 后,应用程序崩溃。下面是我的主要课程。

Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await Firebase.initializeApp();

runApp(EasyLocalization(
 child: MyApp(),
 path: "assets/langs",
 saveLocale: true,
 supportedLocales: [
  Locale('en', 'US'),
  Locale('en', 'GB'),
  Locale('es', 'ES'),
 ],
));
}

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
  providers: [
    Provider<AuthenticationProvider>(
      create: (_) => AuthenticationProvider(FirebaseAuth.instance),
    ),
    StreamProvider(
        create: (context) =>
            context.read<AuthenticationProvider>().authState,
        initialData: null,
        child: Authenticate())
  ],
  child: ScreenUtilInit(
    builder: () => MaterialApp(
      builder: (context, child) {
        return ScrollConfiguration(
          //Removes the whole app's scroll glow
          behavior: MyBehavior(),
          child: child!,
        );
      },
      title: 'SampleApp',
      debugShowCheckedModeBanner: false,
      theme: theme(),
      localizationsDelegates: context.localizationDelegates,
      supportedLocales: context.supportedLocales,
      locale: context.locale,
      home: Authenticate(),
      routes: routes,
    ),
  ),
);
}
}

class Authenticate extends StatelessWidget {
@override
Widget build(BuildContext context) {
final firebaseUser = context.watch<User>();

if (firebaseUser != null) {
  FirebaseFirestore.instance
      .collection('user')
      .doc(firebaseUser.uid)
      .get()
      .then((value) {
    UserData.name = value.data()!['name'];
    UserData.age = value.data()!['age'];
  });
  return View1();
}
return View2();
}
}

class MyBehavior extends ScrollBehavior {
@override
Widget buildViewportChrome(
  BuildContext context, Widget child, AxisDirection axisDirection) {
return child;
}
}

应用程序崩溃并出现以下异常

在构建 Authenticate(dirty) 时引发了以下 ProviderNotFoundException: 错误:在此 Authenticate Widget 上方找不到正确的 Provider

发生这种情况是因为您使用了不包含提供程序的 BuildContext 你的选择。有几种常见的情况:

  • 您在 main.dart 中添加了一个新提供程序并执行了热重载。 要修复,请执行热重启。

  • 您尝试读取的提供程序位于不同的路径中。

    提供者是“范围的”。因此,如果您在路线内插入提供者,那么 其他路由将无法访问该提供程序。

  • 您使用了 BuildContext,它是您尝试读取的提供程序的祖先。

    确保 Authenticate 在您的 MultiProvider/Provider 下。 这通常发生在您创建提供程序并尝试立即读取它时。

【问题讨论】:

  • 同样的问题,你解决了吗?

标签: dart flutter-provider dart-null-safety flutter-streambuilder


【解决方案1】:

答案很简单。我试图监听的变量应该可以为空。

所以,基本上

final firebaseUser = context.watch<User?>();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    • 2020-07-19
    • 2021-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    相关资源
    最近更新 更多