将构建函数延迟到初始化完成,Flutter

huangapple go评论59阅读模式
英文:

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()**方法时,计算尚未完成,并且尝试访问尚未填充数据的某些列表,导致以下错误:

构建时抛出以下RangeErrorI/flutter (23729): RangeErrorindex):无效值:有效值范围为空:0

我尝试使用Future,但未能正确执行。构建始终在完全初始化之前执行。

英文:

In the initState() of my StatefulWidget, I am calling a function called initializeNewGrid():

void initState() {
  // get abbacus provider
  abbacusProvider = Provider.of&lt;AbbacusProvider&gt;(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&lt;AbbacusProvider&gt;(context, listen: false);
      // initialize new abbacus
      abbacusProvider.initializeNewGrid(reset: false);
    });
  }

huangapple
  • 本文由 发表于 2023年7月20日 18:28:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76728954.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定