Search code examples
flutterasynchronousasync-awaitsharedpreferences

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

  • 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(),
                  ),
                );
              },
            )