【问题标题】:Flutter. Could not find the correct Provider<ThemeChanger> above this Home Widget扑。在此主页小部件上方找不到正确的 Provider<ThemeChanger>
【发布时间】: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


    【解决方案1】:

    改变这个:

    create: (_) => ThemeNotifier(),
    

    到这里:

    create: (context) => ThemeNotifier(),
    

    【讨论】:

    • return ChangeNotifierProvider(
    • 错误提示“在此主页小部件上方找不到正确的提供程序”我没有看到您的名为 Home 的小部件的代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2021-10-27
    • 2021-01-27
    相关资源
    最近更新 更多