Flutter Getx Providers get fired twice

Issue

I’m using the Getx package to manage my app state,

there is something wired happening,

all the providers get initialized multiple times

this is my initialization method

Future<void> main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
  ErrorWidget.builder = (e) => ErrorScreen(e.exception);

  await App.initializeProviders();
  if (Get.find<AuthProvider>().isAuth) await App.initializeUserProviders();


  runApp(const Appi());
}


class Appi extends StatelessWidget {
  const Appi({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

and these is the two methods that I use to initialise the providers

first core providers

static initializeProviders() async {
    try {
      Get.lazyPut<AuthProvider>(() => AuthProvider(), fenix: true);
      Get.lazyPut<SettingsProvider>(() => SettingsProvider(), fenix: true);
      Get.put<NotificationsProvider>(NotificationsProvider(), permanent: true);
      await Get.find<AuthProvider>().load();
      await Get.find<SettingsProvider>().load();
      await FirebasePlugin.initializeApp();
    } catch (e) {
      //
      print(e);
    }
  }

and second for the authenticated users

 static initializeUserProviders() async {
    try {
      Get.lazyPut<MainProvider>(() => MainProvider(), fenix: true);
      Get.lazyPut<FiltersProvider>(() => FiltersProvider(), fenix: true);
      Get.lazyPut<CartProvider>(() => CartProvider(), fenix: true);
      Get.lazyPut<SearchProvider>(() => SearchProvider(), fenix: true);
      // Get.lazyPut(() => HomeProvider(), fenix: true);
      // Get.find<HomeProvider>().load();
      Get.find<NotificationsProvider>().load();
      Get.find<FiltersProvider>().load();
      Get.find<CartProvider>().load();
    } catch (e) {
      //
    }
  }

and I got this in the debugging console


[GETX] Instance "NotificationsProvider" has been created
[GETX] Instance "NotificationsProvider" has been initialized
2[GETX] Instance "AuthProvider" has been created
2[GETX] Instance "AuthProvider" has been initialized
[GETX] Instance "NotificationsProvider" has been created
[GETX] Instance "NotificationsProvider" has been initialized
[GETX] Instance "AuthProvider" has been created
[GETX] Instance "AuthProvider" has been initialized
2[GETX] Instance "SettingsProvider" has been created
2[GETX] Instance "SettingsProvider" has been initialized
[GETX] Instance "SettingsProvider" has been created
[GETX] Instance "SettingsProvider" has been initialized
2
W/FLTFireMsgService( 5927): Attempted to start a duplicate background isolate. Returning...

Note that I use exactly the same methods and the same way in another app and everything works there to find,

// auth load 

 Future<void> load() async {
    if (_profile.value != null && _token.value != null) return;
    final localStorage = await SharedPreferences.getInstance();
    final lt1 = localStorage.getString('somekey1');
    final lt2 = localStorage.getString('somekey2');
    final lt3 = localStorage.getString('somekey3');
    final localProfile = localStorage.getString('_up');
    if (lt1 != null && lt2 != null && lt3 != null && localProfile != null) {
      _token.value = lt1 + lt2 + lt3;
      final profile = json.decode(localProfile);
      _profile.value = UserModel.fromJson(profile, avatar: profile['avatar']);
      update();
      return;
    }
  }






// filters load 
load() async {
    await App.getData('PRD/filters.php').then((value) {
      if (value != null) {
        final platforms = value["brands"] as Map<String, dynamic>;
        final stores = value["stores"] as Map<String, dynamic>;
        setFilters(stores.values.toList(), platforms.values.toList());
      }
    }).catchError((e) {
      throw e;
      // TODO:: handle error
    });
  }

void setFilters(
    List<dynamic> stores,
    List<dynamic> platforms, {
    bool local = false,
  }) {
    if (stores.isEmpty || platforms.isEmpty) return;
    _allPlatforms.value.clear();
    _allStores.value.clear();
    _allPlatforms.value.add(Filter.getDefault(isPlatform: true));
    _allStores.value.add(Filter.getDefault());
    for (var platform in platforms) {
      _allPlatforms.value.add(Filter.fromJson(platform, isPlatform: true));
    }
    for (var store in stores) {
      _allStores.value.add(Filter.fromJson(store));
    }
    if (!local) {
      SharedPreferences.getInstance().then((prefs) {
        prefs.setString("allPlatforms", jsonEncode(platforms));
        prefs.setString("allStores", jsonEncode(stores));
      });
    }
    update();
  }








// notification load 
 Future<void> load() async {
    final result = await _database.getAll();
    if (result.length == _notifications.value.length) return;
    _notifications.value.clear();
    _notifications.value.addAll(result
        .map((e) => NotificationModel.fromJson({
              'id': e['id'],
              'message': e['title'],
              'type': e['type'],
              'type_id': e['type_id'],
              'level': e['level'],
              'is_new': e['is_new'],
            }))
        .toList());

    if (_notifications.value.isNotEmpty) {
      _notifications.value
          .sort((a, b) => int.parse(a.id).compareTo(int.parse(b.id)));
    }
    update();
  }




// cart load 
Future<void> load() async {
    try {
      final items = await database.getAll();
      _cartItems.clear();
      for (var e in items) {
        _cartItems.add(CartItem.fromJson(e));
      }
      update();
    } catch (e) {
      rethrow;
    }
  }

Solution

I fix this issue as following:

I create a new flutter project,
I move my lib folder to the new project.

I guess it was a bug in VSCode or something in the android folder.

Answered By – Mocha

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *