我已迁移到 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 下。这通常发生在您创建提供程序并尝试立即读取它时。