how to retrieve a value from shared preferences instantly? - FLUTTER

296

you can use dependency injection follow these steps : get it package

create a Separate dart containing the following code file like this:

GetIt locator = GetIt.instance;
Future<void> setupLocator() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
locator.registerLazySingleton<SharedPreferences>(() => sharedPreferences);  
}

call the setupLocator() method and wait for it in your main function

 void main() async {
    await setupLocator();
    runApp(App());
    }

access SharedPreferences Instance from anywhere like this: locator(); now the SharedPreferences Instance if available anywhere in your project please note that you dont have to wait for getting the Instance anymore, because you have only one Instance sharable across the application

    bool getSwitchState() {
    final prefs = locator<SharedPreferences>();
    SettingsPage.switched = prefs.getBool("switched")!;
    print(SettingsPage.switched);

    return SettingsPage.switched;
   }
Share:
296
Admin
Author by

Admin

Updated on December 31, 2022

Comments

  • Admin
    Admin over 1 year

    I'm trying to show a page as an initial login, this is only displayed when my switch value is set to true. The switch value is stored with shared preferences but when I open the application it is not recovered, only after an application update is it actually recovered. how can i get it to be recovered instantly when i open my application?

    below the code:

    Future<bool> saveSwitchState(bool value) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setBool("switched", value);
        print('Switch Value saved $value');
        return prefs.setBool("switched", value);
      }
    
    Future<bool> getSwitchState() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        SettingsPage.switched = prefs.getBool("switched")!;
        print(SettingsPage.switched);
    
        return SettingsPage.switched;
      }
    

    on another page then the value that is actually recovered:

    if(AuthPage.authenticated == false && SettingsPage.switched == true ) {
          yield ProfileNoAuth();
          return; }
    
  • Admin
    Admin over 2 years
    ok thanks, but do I have to change something in the code I wrote above? and where do I call it locator ()?
  • Admin
    Admin over 2 years
    you are great ! god bless u
  • MOUKZ
    MOUKZ over 2 years
    glad i could help <3 feel free to ask if you needed help refactoring your code
  • Admin
    Admin over 2 years
    Could you possibly help me on my last question asked?
  • MOUKZ
    MOUKZ over 2 years
    sure!! i just checked, did you get your answer??