SharedPreferences在真实设备上不起作用FLUTTER [英] SharedPreferences not working on real device FLUTTER

查看:60
本文介绍了SharedPreferences在真实设备上不起作用FLUTTER的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用SharedPreferences记住了用户名和密码,以便下次登录时无需输入密码.当我使用USB电缆使用真实设备进行调试时,它运行良好.但是,当我构建APK并安装它时,它无法在我的设备中运行.我不知道我在想什么.

I used SharedPreferences to make remember username and password to log in next time without asking a password. It was working well when I debug using my real device with USB cable. But it's not working in my device when I build APK and install it. I don't know what I'm missing.

我这样将数据保存在登录页面中

I save data in login page like this`

Future<Null> loginUser(isLogin, name, fac, year, gender) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('Name', name);
prefs.setString('IsLogin', isLogin);
prefs.setString('Faculty', fac);
prefs.setString('Year', year);
prefs.setString('Gender', gender);
prefs.setString('Email', email);

print(prefs.getString('Faculty'));

}

我在主页上使用了此代码....

I used this code in main page....

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
  Widget build(BuildContext context) {
    return NewMain();
  }
}

class NewMain extends StatefulWidget {
  @override
  _NewMainState createState() => _NewMainState();
}

class _NewMainState extends State<NewMain> {
  var name, fac, year, gender, email;
  var goToLogin = true;
  @override
  void initState() {
    // TODO: implement initState
    checkRem();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (goToLogin)
      return MaterialApp(
        home: Login(),
      );
    else
      return MaterialApp(
        home: MainClass(name, fac, year, gender, email),
      );
  }

  void checkRem() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.getString('IsLogin') == 'Yes') {
      goToLogin = false;
      fac = prefs.getString('Faculty');
      name = prefs.getString('Name');
      gender = prefs.getString('Gender');
      year = prefs.getString('Year');
      email = prefs.getString('Email');
    }
  }
}

如果goToLogin为false,它将移至MainClass.它在调试中运行完美.在内置的APK应用程序上无法正常运行.

It will move to MainClass if goToLogin is false. It's working perfectly in debug. It's not working on the built apk app.

已解决

这是我的IDE的问题.更新并修复

It was problem with my IDE. Updated and fixed

推荐答案

问题是您调用了 checkRem(),这在 initState()中是异步的,因此调用了build方法在完全执行 checkRem()之前.

Problem is u calling checkRem() which is async in initState() so build method getting called before complete execution of checkRem().

Soln:在完全执行方法之后,用 futureBuilder()包裹它或调用 setState()

Soln: wrap it with futureBuilder() or calling setState() after complete execution of method

这篇关于SharedPreferences在真实设备上不起作用FLUTTER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆