Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I get preferences from shared preferences in a method that can't by async in Flutter?

I want to get the bool of a shared pref to decide which Widget should get loaded, but the method cant be async or to bool cant get the value because it is not allowed to "await" the value. I have tried fixing it, but it mostly fails because "home" can’t receive a future widget…, is there another way how I could do this?

void main() => runApp(MyApp());
setloginbool() async{
  SharedPreferences prefs = await SharedPreferences.getInstance();
  prefs.setBool("savelogin", true);
}

Future<bool> getloginbool() async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  bool savelogin = prefs.getBool("savelogin") ?? false;
  return savelogin;
}



class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'KHS Plan',
      theme: (ThemeData(
        textTheme: const TextTheme(
          bodyText1: TextStyle(fontSize: 14)
        )
      )),
      home: checkifpassword(),
    );
  }

}
Widget checkifpassword() {
    bool s = await getloginbool();
    if(s){
      return const Login();
    } else {
      return const MyHomePage();
    }
  }


//This does not work as well
checkifpassword() async {
  bool s = await getloginbool();
    if(s){
      return const Login();
    } else {
      return const MyHomePage();
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use FutureBuilder on Home

 Future<bool> checkifpassword() async {
//perfrom your async operation and return bool
    return await Future.delayed(Duration(seconds: 2), () {
      return true;

    });
  }

And home

 home: FutureBuilder<bool>(
          future: checkifpassword(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (snapshot.data!) {// for true
                return Login();;
              } else return MyHomePage();
            }
            /// check others state

            return Scaffold(
              body: Center(
                child: CircularProgressIndicator(),
              ),
            );
          },
        )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading