【问题标题】:Flutter:how to delay the build method for sometimeFlutter:如何将构建方法延迟一段时间
【发布时间】:2025-12-28 07:35:12
【问题描述】:

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

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

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

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

//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));
      }    });
}

【问题讨论】:

    标签: flutter sharedpreferences token


    【解决方案1】:

    你可以使用 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));
      });
    }
    

    【讨论】: