【发布时间】:2021-10-22 18:34:23
【问题描述】:
我想在我的代码中添加带有提供程序的主题。我从这个来源改编它。 https://github.com/lohanidamodar/flutter_theme_provider/blob/master/lib/main.dart.
即使是相同的代码,我也得到了这个错误:
"在构建 Home(dirty, state: _HomeState#c900c) 时引发了以下 ProviderNotFoundException:
错误:在此主页小部件上方找不到正确的提供程序”
发生这种情况是因为您使用了不包含提供程序的 BuildContext
您的选择。
void main() async {
setPathUrlStrategy();
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MaterialAppWithTheme());
}
class MaterialAppWithTheme extends StatefulWidget {
@override
_MaterialAppWithThemeState createState() => _MaterialAppWithThemeState();
}
class _MaterialAppWithThemeState extends State<MaterialAppWithTheme> {
@override
void initState() {
super.initState();
AppRouter appRouter = AppRouter(
routes: AppRoutes.routes,
notFoundHandler: AppRoutes.routeNotFoundHandler,
);
appRouter.setupRoutes();
}
@override
Widget build(BuildContext context) {
return ChangeNotifierProvider(
create: (_) => ThemeNotifier(),
child: Consumer<ThemeNotifier>(
builder: (context, ThemeNotifier notifier, child) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: notifier.darkTheme ? dark : light,
onGenerateRoute: AppRouter.router.generator,
);
},
),
);
}
}
【问题讨论】:
标签: flutter