flutter - 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));
} });
}
解决方案
您可以使用 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));
});
}
推荐阅读
- amazon-web-services - ec2 用户数据脚本仅部分执行
- c++ - 使用 SDL2 和 SDL_image 加载 C++ 图像
- scala - 带有当前行条件的 Spark 窗口函数
- c# - 禁用控件上的所有鼠标消息
- mysql - 如何创建 perl 脚本以访问许多主机并更新或执行自定义作业
- javascript - JSON.stringify() - 对象的自定义序列化器
- azure - 获取 PnPUnifiedGroup:代码:Authorization_RequestDenied
- r - 我在 R 中导入了一个通过调查创建的数据集,其中只有数值。但是,一旦我将它加载到 R 中,只会出现 NA
- python - 使用循环检查字符串的标点符号
- javascript - 为什么当 push() 在下面的 for 循环中运行时浏览器崩溃