英文:
Delay build function until initialization, Flutter
问题
在我的StatefulWidget的*initState()中,我调用了一个名为initializeNewGrid()***的函数:
void initState() {
// 获取abbacus提供程序
abbacusProvider = Provider.of<AbbacusProvider>(context, listen: false);
// 初始化新的abbacus
abbacusProvider.initializeNewGrid(reset: false);
}
这个函数调用了一些用于初始化所需变量的更多函数之一,其中一个函数的返回类型为int,执行了许多计算:
int generateProblem({required bool next}) {
//
// 生成新问题的代码
//
// 返回生成问题的解决方案
return computeCorrectSolution();
}
因此,当调用**build()**方法时,计算尚未完成,并且尝试访问尚未填充数据的某些列表,导致以下错误:
构建时抛出以下RangeError:I/flutter (23729): RangeError(index):无效值:有效值范围为空:0
我尝试使用Future,但未能正确执行。构建始终在完全初始化之前执行。
英文:
In the initState() of my StatefulWidget, I am calling a function called initializeNewGrid():
void initState() {
// get abbacus provider
abbacusProvider = Provider.of<AbbacusProvider>(context, listen: false);
// initialize new abbacus
abbacusProvider.initializeNewGrid(reset: false);
}
This function calls some more functions for initialization of the needed variables, one of these functions which has a return type of int is performing a lot of computations:
int generateProblem({required bool next}) {
//
// Code to generate a new problem
//
// return solution of the generated problem
return computeCorrectSolution();
}
such that when build() method is called the computation is not yet completed, and some of the lists that are not yet filled with data are tried to be accessed with the ListView.builder, which results in the following error:
The following RangeError was thrown building: I/flutter (23729): RangeError (index): Invalid value: Valid value range is empty: 0
I have tried using Future but haven't been able to do it properly. The build always executes before the complete initialization.
答案1
得分: 2
尝试将您的initState更改如下所示:
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
// 获取 abbacus 提供者
abbacusProvider = Provider.of<AbbacusProvider>(context, listen: false);
// 初始化新的 abbacus
abbacusProvider.initializeNewGrid(reset: false);
});
}
英文:
Try to change your initState as mentioned below
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) async {
// get abbacus provider
abbacusProvider = Provider.of<AbbacusProvider>(context, listen: false);
// initialize new abbacus
abbacusProvider.initializeNewGrid(reset: false);
});
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论