gpt4 book ai didi

flutter : Why build widget runs first before the initState()?

转载 作者:行者123 更新时间:2023-12-05 03:28:52 25 4
gpt4 key购买 nike

这是我的 controller.dart 文件,它检查用户是否通过验证,然后根据条件返回页面。我的问题是为什么构建小部件先于 initState() 执行?我尝试使用断点调试此代码,并注意到 build() widget 首先运行,然后是 initState()为什么会发生这种情况,我该如何解决?

这是我的代码:

class _ControllerState extends State<Controller> {
late bool auth;
@override
Widget build(BuildContext context) {
return (auth==false) ? Onbording() : IndexPage();
}

@override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((_) async {
await this.checked_if_logged();
});

}
Future<void> checked_if_logged() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
if(prefs.getBool('verified')==true){
setState(() {
auth = true;
});
}else{
setState(() {
auth = false;
});
}
}
}

这是我的调试代码的快照,其中蓝线显示它在 init 之前先运行,因为 bool authlate 类型,所以它抛出 lateInitializationErrror 之后调用 initState() 初始化 auth 变量,重建小部件并消除错误 enter image description here

更新:我注意到当我用 check_if_logged() 替换 WidgetsBinding.instance!.addPostFrameCallback((_) 时,initState() 正在调用首先但在 check_if_logged() 完成之前,构建小部件首先执行,再次抛出 lateInitializationError

最佳答案

我不知道你从哪里得到 addPostFrameCallback 或者你想实现什么,但这不是方法。

你的问题是,checked_if_loggedasync 并且没有办法 await 中的 async 方法初始化状态。这是设计使然,没有办法解决。

处理此问题的正确方法是使用 FutureBuilder 小部件。

参见 What is a Future and how do I use it?

关于 flutter : Why build widget runs first before the initState()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71172845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com