【发布时间】: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