Flutter 颤振:颤振共享偏好don';不工作,不保存用户名编辑#1

Flutter 颤振:颤振共享偏好don';不工作,不保存用户名编辑#1,flutter,session,Flutter,Session,我有一个应用程序包含登录和注册系统,该系统工作正常。 问题是我想让用户通过使用flatter_会话包登录,但不起作用。 首先,我有一个预加载页面,其中包含使用以下功能检查用户是否登录: void gotoTabPae() { print('ok'); Future.delayed(const Duration(milliseconds: 3000), () { Navigator.of(context).pushReplacementNamed('tabs');

我有一个应用程序包含登录和注册系统,该系统工作正常。 问题是我想让用户通过使用flatter_会话包登录,但不起作用。 首先,我有一个预加载页面,其中包含使用以下功能检查用户是否登录:

void gotoTabPae() {
    print('ok');
    Future.delayed(const Duration(milliseconds: 3000), () {
      Navigator.of(context).pushReplacementNamed('tabs');
    });
  }

  void gotoLoginPage() {
    print('no');
    Future.delayed(const Duration(milliseconds: 3000), () {
      Navigator.of(context).pushReplacementNamed('login');
    });
  }

  getuser() async {
    var loginedUser;
    SharedPreferences preferences = await SharedPreferences.getInstance();
setState(() {
  loginedUser= preferences.getString('username');
});
    loginedUser != null ? gotoTabPae() : gotoLoginPage();
  }

  @override
  void initState() {
    getuser();
    super.initState();
  }
当我运行应用程序并登录时,当我重新启动应用程序时,它必须转到“选项卡”页面,但用户名的值始终为空,因此它加载登录页面,登录功能为:

login() async {
    var formdata = formLoginKey.currentState;
    if (formdata.validate()) {
      formdata.save();

      var data = {'username': username.text, 'password': password.text};
      var url =xxxx/api/controller/users/login_user.php";
      var response = await http.post(url, body: data);
      var responsebody = jsonDecode(response.body);
      if (responsebody['status'] == 'success') {
        SharedPreferences pref = await SharedPreferences.getInstance();
      pref.setString('username', username.text);
        Navigator.of(context).pushReplacementNamed('tabs');
      } else {
        _showDialog(context, responsebody['status']);
      }
    } else {
    }
  }
但在“选项卡”页面中,加载会话用户名对应项:

  getuser() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
var logineduser = preferences.getString('username');
  }

  @override
  void initState() {
    getuser();
    super.initState();
  }

我怎样才能解决这个问题?我的错误在哪里?您的代码正在
initSate()
方法中运行
getuser()
方法,该方法甚至在
super.initState()之前运行。这就是该值无法加载的原因,这使得它为空。您应该在构建函数中使用它。
您的代码可能如下所示:

@override
  Widget build(BuildContext context) {
    var loginedUser;
    loginedUser = await FlutterSession().get('username');
    loginedUser != null ? return ClassName()(tabs.dart) : return ClassName()(login.dart);
  }

我认为在您的登录函数中,pref.setString('username',username.text)是在收到响应之前运行的。你能试试这个吗

http.post(url, body: data).then((response) {
  var responsebody = jsonDecode(response.body);
  if (responsebody['status'] == 'success') {
    SharedPreferences pref = await SharedPreferences.getInstance();
    pref.setString('username', username.text);
    Navigator.of(context).pushReplacementNamed('tabs');
  }
});
让我知道结果