如何解决迁移到空安全版本 Provider 5.0.0 后对 Stream Provider 的更改
我已迁移到 dart null 安全版本。迁移功能中的命令修复了大多数问题。但是,我有一个 Stream Provider,它使用 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: 错误:无法在此身份验证小部件上方找到正确的提供者
发生这种情况是因为您使用了不包含提供程序的 BuildContext
你的选择。有几种常见的情况:
-
您尝试读取的提供程序位于不同的路径中。
提供者是“有范围的”。因此,如果您在路由中插入 provider,则 其他路由将无法访问该提供程序。
-
您使用了
BuildContext
,它是您尝试读取的提供程序的祖先。确保 Authenticate 在您的 MultiProvider/Provider 下。 这通常发生在您创建提供程序并尝试立即读取它时。
解决方法
答案很简单。我试图监听的变量应该可以为空。
所以,基本上
final firebaseUser = context.watch<User?>();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。