Error: Could not find the correct Provider<ThemeNotifier> above this VideosYou Widget

Viewed 34

I have this error when I try to open a new main.dart For example: I need to open main2.dart from main.dart but still shows Provider(ThemeNotifier).

main.dart

MenuItem(
                      title: "Click".tr(),
                      onPressed: (){
                        Navigator.push(
                            context,
                            MaterialPageRoute(builder: (context) => Click())
                        );
                      },
                    ),
                    MenuItem(
                      title: "Extra".tr(),
                      onPressed: () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(builder: (context) => MyApp2()),
                        );
                      },
                    ),

And this is my main2.dart

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  Wakelock.enable();
  await Firebase.initializeApp(
   // options: DefaultFirebaseOptions.currentPlatform,
  );
  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  await Hive.initFlutter();
  await Hive.openBox(authBox);
  await Hive.openBox(userDetailsBox);
  await Hive.openBox(settingsBox);
  SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
    statusBarIconBrightness:
        DesignConfig.isDark ? Brightness.light : Brightness.dark,

    // status bar color
  ));
  final pushNotificationService = PushNotificationService(firebaseMessaging);
  //pushNotificationService.initialise();
  runApp(ChangeNotifierProvider<ThemeNotifier>(
      create: (BuildContext context) {
        String theme = SettingsLocalDataSource().theme();

        if (theme == StringRes.darkThemeKey) {
          ISDARK = "true";
        } else {
          ISDARK = "false";
        }
        var brightness = SchedulerBinding.instance.window.platformBrightness;
        ISDARK = (brightness == Brightness.dark).toString();
        return ThemeNotifier(theme == StringRes.lightThemeKey
            ? ThemeMode.light
            : ThemeMode.dark);
      },
      child: const MyApp2()));
}

class MyApp2 extends StatefulWidget {
  const MyApp2({Key key}) : super(key: key);

  @override
  State<MyApp2> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp2> {
  @override
  Widget build(BuildContext context) {
    final themeNotifier = Provider.of<ThemeNotifier>(context);
    return Shortcuts(
        shortcuts: <LogicalKeySet, Intent>{
          LogicalKeySet(LogicalKeyboardKey.select): const ActivateIntent(),
        },
        child: MultiProvider(
            providers: [
              ChangeNotifierProvider(
                create: (_) => Provider1(),
              ),
              ChangeNotifierProvider(
                create: (_) => Provider2(),
              ),
              ChangeNotifierProvider(
                create: (_) => Provider3(),
              ),
              ChangeNotifierProvider(
                create: (_) => Provider4(),
              ),
              ChangeNotifierProvider(
                create: (_) => Provider5(),
              ),
            ],
            child: MaterialApp(
              builder: (context, widget) {
                return Directionality(
                    textDirection:
                        TextDirection.ltr, // set here your text direction
                    child: ScrollConfiguration(
                        behavior: GlobalScrollBehavior(), child: widget));
              },
              title: appName,
              theme: ThemeData(
                      shadowColor: primaryColor.withOpacity(0.25),
                      brightness: Brightness.light,
                      primaryColor: primaryColor,
                      scaffoldBackgroundColor: scaffoldBackgroundColor,
                      backgroundColor: backgroundColor,
                      canvasColor: blackColor,
                      hintColor: iconHintColor,
              ),
              darkTheme: ThemeData(
                      shadowColor: darkPrimaryColor.withOpacity(0.25),
                      brightness: Brightness.dark,
                      primaryColor: darkPrimaryColor,
                      scaffoldBackgroundColor: darkScaffoldBackgroundColor,
                      backgroundColor: darkBackgroundColor,
                      canvasColor: darkBlackColor,
                      hintColor: darkIconHint,
                      
              ),
              themeMode: themeNotifier.getThemeMode(),
              initialRoute: Routes.splash,
              onGenerateRoute: Routes.onGenerateRoute,
            )));
  }
}

but when I try to open a main2.dart the error shows. This happens because you used a BuildContext that does not include the provider of your choice. There are a few common scenarios:

  • You added a new provider in your main.dart and performed a hot-reload. To fix, perform a hot-restart.

  • The provider you are trying to read is in a different route.

    Providers are "scoped". So if you insert of provider inside a route, then other routes will not be able to access that provider.

  • You used a BuildContext that is an ancestor of the provider you are trying to read.

    Make sure that VideosYou is under your MultiProvider/Provider. This usually happens when you are creating a provider and trying to read it immediately.

1 Answers

The main function is the entry point of an application. When a new route is pushed, only MyApp2 is instantiated, main is not called.

Related