Using SharedPreferences to set login state and ret

2019-02-20 21:09发布

问题:

I have an flutter app in which I have to check the login status when the app is launched and call the relevant screen accordingly.

The code used to launch the app:

class MyApp extends StatefulWidget {
  @override
  MyAppState createState() {
    return new MyAppState();
  }
}


class MyAppState extends State<MyApp> {

bool isLoggedIn;

    Future<bool> getLoginState() async{
      SharedPreferences pf =  await SharedPreferences.getInstance();
      bool loginState = pf.getBool('loginState');
      return loginState;
      // return pf.commit();
    }

  @override
  Widget build(BuildContext context) {

   getLoginState().then((isAuth){
      this.isLoggedIn = isAuth;
   });


    if(this.isLoggedIn) {return Container(child: Text('Logged In'));}
    else {return Container(child: Text('Not Logged In));}

  }
}

I am able to save the SharedPreference and retrieve it here, the issue is that as getLoginState() is an async function, this.isLoggedIn is null by the time the if condition is executed. The boolean assertion fails in the if statement and the app crashes.

How do I ensure that the bool variable isLoggedIn used in the if condition has a value when the if statement is executed?

Any help would be appreciated.

回答1:

You can use FutureBuilder to solve this problem.

@override
Widget build(BuildContext context) {
 new FutureBuilder<String>(
    future: getLoginState(),
    builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
      switch (snapshot.connectionState) {
        case ConnectionState.active:
        case ConnectionState.waiting:
          return new Text('Loading...');
        case ConnectionState.done:
          if (snapshot.hasData) {
            loginState = snapshot.data;
            if(loginState) {
             return Container(child: Text('Logged In'));
            }
            else {
             return Container(child: Text('Not Logged In));
            }
          } else {
           return  Container(child: Text('Error..));
          }
      }
    },
  )
 }

Note: we don't need isLoggedIn state variable.



标签: dart flutter