Why might a function not get called in initState(){ super.initState()} in flutter, but work perfectly fine if called later in the same page?

痴心易碎 提交于 2021-02-15 07:37:08

问题


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]),
    }
  }

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(); 
}

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:


problem here is :

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

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

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

Soln:

  1. Either use futurebuilder in build() method

or

  1. use bool loading = true & set it to false after async method is complete & call setState() so that build() method is called again


来源:https://stackoverflow.com/questions/61121266/why-might-a-function-not-get-called-in-initstate-super-initstate-in-flutte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!