首页 > 解决方案 > Flutter:如何将构建方法延迟一段时间

问题描述

我正在处理我的项目,其中包括注册和登录,并且我还在保存登录或注册时从 API 收到的 JSON Web 令牌(在 SharedPreferences 中)。

我创建了一个异步方法,该方法检测令牌是否已保存在 sharedPreferences 中(因此用户经过身份验证并被授权访问主页,无需再次输入用户名和密码)

当我在登录页面的 initState() 方法中使用此方法时(在我的例子中,显示登录表单的页面),登录页面显示 1 秒或更短时间,然后令牌在 Future 之后变为可用checkAuthentication 返回的数据变为 available ,然后用户被重定向到主页,

我想让着陆页根本不出现,除非找不到令牌

//by the way AuthData is just a custom class

Future<AuthData> checkAuthentication() async {
    AuthData authData = new AuthData();
    SharedPreferences preferences = await SharedPreferences.getInstance();

    if(preferences.containsKey("token")){
      authData.token =  preferences.get("token");
      return authData;
    }
    return null;
  }


// initState method
@override
  void initState() {
    super.initState();
checkAuthentication().then((AuthData data){
   if(data != null){
          Navigator.of(context).pushNamedAndRemoveUntil("/home-page", 
ModalRoute.withName(null));
      }    });
}

标签: fluttersharedpreferencestoken

解决方案


您可以使用 setState

bool isLogin = false;

@override
  void initState() {
    super.initState();
checkAuthentication().then((AuthData data){
       setState(() {
        if(!data)
        isLogin = true;
      });
      if(isLogin)
         Navigator.of(context).pushNamedAndRemoveUntil("/home-page",
         ModalRoute.withName(null));
  });
}

推荐阅读