如何使用共享首选项使用户保持登录状态

时间:2020-02-20 19:05:53

标签: firebase flutter sharedpreferences

我已经为使用Firebase身份验证的flutter应用程序创建了一个登录页面。有人可以帮助我在其中使用共享首选项,以便即使用户杀死了该应用程序也可以保持登录状态

1 个答案:

答案 0 :(得分:0)

好吧,在登录功能中,如果验证成功,则应该将数据保留在sharePreference中;

/// your statefull code

void login() {
   // get the inputValues;

   // if validation success do this
   this._persistUserInfo();
}


void _persistUserInfo() async {
  final sharePrefsInstance = await SharedPreferences.getInstance();

  sharePrefsInstance .setString("email", EMAIL_VALUE);
  sharePrefsInstance .setString("password", _PASSWORD_VALUE);

}

/// your other statefull code;

上面的代码将信息保留在设备上;

要检索数据,请在 LoginScreen initState 中执行

 @override
  void initState() {
    super.initState();
    Future.delayed(
      Duration(seconds: 3),
      () async {
          final sharePrefsInstance = await SharedPreferences.getInstance();

          final email = sharePrefsInstance.getString("email");
          final password  =  sharePrefsInstance.getString("password");

          if( email != null && password != null) {
             // navigate to your other screen since the user is authenticated
          }
      },
    );
  }