【问题标题】:Shared Prefrences data are gone after restarting or reopening the app in flutter重新启动或重新打开应用程序后,共享首选项数据消失了
【发布时间】:2021-06-09 14:39:53
【问题描述】:

我在我的 futter 应用程序中使用包 shared_preferences 来保存登录..

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter
  localize_and_translate: ^1.1.1+6
  flutter_fadein: ^1.1.1
  http: ^0.12.2
  loading_overlay: ^0.2.1
  fluttertoast: ^7.1.1
  image_picker: ^0.6.7+12
  shared_preferences: ^0.5.12+4  // this line

保存数据

  Future saveLoginData(LoginModel loginModel) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    print(loginModel.token); //gives me the right string 
    prefs.setString('theToken', loginModel.token);
    print(prefs.getString('theToken')); //gives me the right string
    prefs.setBool('logged', true);
    prefs.setString('type', 'vendor');
    prefs.setString('mobileNumber', loginModel.username);
}
  

调用数据

// this function is called while starting the login screen ,to see if the user have to login or just can skip tothe home page
  Future<String> checkIfLogged() async {
    return await SharedPreferences.getInstance().then((prefs) {
      String theToken = prefs.getString('theToken');
      print(theToken); //outputs null
      return theToken; //returns null
    });
  }

当尝试在应用程序的同一个打开实例中调用保存的数据时,它被完美调用,但是当应用程序关闭并在登录屏幕的initstate 处检查数据时。它把一切都归还空!!一个

【问题讨论】:

    标签: android flutter dart sharedpreferences


    【解决方案1】:

    尝试这种方式,因为您将 awaitthen 语法混合在一起,并且实际上可能不会返回

      Future<String> checkIfLogged() async {
        var prefs= await SharedPreferences.getInstance()
          String theToken = prefs.getString('theToken');
          print(theToken); //outputs null
          return theToken; //returns null
        
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-08
      • 1970-01-01
      相关资源
      最近更新 更多