为什么不能在flit中的initState(){super.initState()}中调用函数,但是如果稍后在同一页面中调用,则可以正常工作吗? [英] Why might a function not get called in initState(){ super.initState()} in flutter, but work perfectly fine if called later in the same page?

查看:40
本文介绍了为什么不能在flit中的initState(){super.initState()}中调用函数,但是如果稍后在同一页面中调用,则可以正常工作吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为splitVendorMainCategory的函数,该函数将一个List拆分为两个子List,描述如下:

I have a function named splitVendorMainCategory, which simply splits a List into two subLists, described as:

List vendorMainCategory = ['one', 'two', 'three', 'four'];

Future splitVendorMainCategory() async {
 for (int i=0; i< (vendorMainCategoryLength); i+=2){

      vendorMainCategoryC1.add(vendorMainCategory[i]),                    
    },

    for(int j = 1; j < vendorMainCategoryLength; j+=2){
      vendorMainCategoryC2.add(vendorMainCategory[j]),
    }
  }

我在页面初始化时就调用它,但是它返回两个空的子列表,而List VendorMainCategory包含元素.我将该函数称为:

And I call it right at the initialisation of the page, but it returns two empty sub-lists, while the List VendorMainCategory contains elements. I call the function as:

 @override
 initState() {
   splitVendorMainCategory();
   super.initState(); 
}

但是,当我在同一页面的"body"中调用相同的函数时,它将返回预期的结果.

However, when I call the same function in 'body' of the same page, it returns the expected result.

vendorMainCategoryC1 = [one, three]
vendorMainCategoryC2 = [two, four]    

是什么导致该函数在页面初始化时不被调用,但是在另一个窗口小部件中调用时使其完全正常工作?当我尝试以任何一种方式运行它时,都不会引发任何错误,只是我得到了两个不同的结果.任何帮助将不胜感激.

What could be causing the function to not be called at the initialisation of the page, but make it work completely fine when called inside another widget? No error is thrown when I try to run it either way, just that I get two different results. Any help will be highly appreciated.

推荐答案

问题在这里是

  1. splitVendorMainCategory()方法是 async ,这意味着需要一些时间才能完成其执行

  1. splitVendorMainCategory() method is async which mean it takes some time to complete its execution

init()方法是非异步的,这意味着它不会等待任何异步方法.

init() method is non-async that mean it will not await to any async method.

因此,每当您在完成执行之前调用 splitVendorMainCategory()时,都会将&称为&开始构建小部件

so whenever u call splitVendorMainCategory() before it completes its execution build() method is called & started building widgets

Soln:

  1. build()方法中使用 futurebuilder
  1. Either use futurebuilder in build() method

  1. 使用 bool loading = true &在异步方法完成后将其设置为 false .调用 setState(),以便再次调用 build()方法
  1. use bool loading = true & set it to false after async method is complete & call setState() so that build() method is called again

这篇关于为什么不能在flit中的initState(){super.initState()}中调用函数,但是如果稍后在同一页面中调用,则可以正常工作吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆