Search code examples
flutterbloc

Trying to understand bloc code but getting (runZoned is deprecated, and Zone mismatch)


I am teaching myself bloc but there is this segment of code which is deprecated:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  BlocOverrides.runZoned(
        () async {
      DioHelper.init();
      await CacheHelper.init();
      final locale =
          CacheHelper.getDataFromSharedPreference(key: 'language') ?? "ar";
      delegate = await LocalizationDelegate.create(
        fallbackLocale: locale,
        supportedLocales: ['ar', 'en'],
      );
      await delegate.changeLocale(Locale(locale));
      runApp(MyApp(
        appRouter: AppRouter(),
      ));
    },
    blocObserver: MyBlocObserver(),
  );
}

which I think resulted in Zone mismatch exception .

I tried to learn how to fix it but I didn't know where to put the rest of the code which includes (Initializations & localization).

It would be great if someone helped teaching me the problem, and how to fix it because I don't understand this part really well


Solution

  • I was able to restructure the code like that:

    //Initialisations
      WidgetsFlutterBinding.ensureInitialized();
      NotificationUtil.init();
      DioHelper.init();
      await CacheHelper.init();
    
      //Bloc Observer
      Bloc.observer = MyBlocObserver();
    
      //Locals
      final locale =
          CacheHelper.getDataFromSharedPreference(key: 'language') ?? "en";
      delegate = await LocalizationDelegate.create(
        fallbackLocale: locale,
        supportedLocales: ['ar', 'en'],
      );
      await delegate.changeLocale(Locale(locale));
    
      //runApp, with appRouter
      runApp(MyApp(
        appRouter: AppRouter(),
      ));
    

    The whole point is to just remove runZoned(), and simply put the rest of the code outside of it, and then you can separately call Bloc.observer = MyBlocObserver();