Defining async call in init state in flutter

Issue

In the below code I have been trying to initialize the method checkStatus() with the values I get from the provider but since there is a loading delay to the provider generated data I am not ale to initialize the method in the init state. Is there a alternative way I could use here?

@override
      void initState() {
        // TODO: implement initState
        super.initState();
        final interestDetail = Provider.of<InterestProvider>(context, listen: false);
        interestDetail.getData(context);
    

checkStatus(interestDetail.interest.subcategoryData,interestDetail.interest.customerSelectedSubcatIds);
      }
    
      List<int> checkStatus(a, c){
        for (var i = 0, len1 = a.length; i < len1; i++) {
          for (var j = 0, len2 = c.length; j < len2; j++) {
            if (a[i].id == c[j]) {
              _selectedIndexList.add(j);
              _selectedCatList.add(j + 1);
              check = true;
              break;
            }
          }
        }
        print(check);
        return _selectedIndexList;
      }

Solution

you can modify your source code like below:

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    Future.delayed(Duration.zero, () {
       final interestDetail = Provider.of<InterestProvider>(context, listen: false);
        interestDetail.getData(context);
    

checkStatus(interestDetail.interest.subcategoryData,interestDetail.interest.customerSelectedSubcatIds);
    });
  }
    List<int> checkStatus(a, c){
        for (var i = 0, len1 = a.length; i < len1; i++) {
          for (var j = 0, len2 = c.length; j < len2; j++) {
            if (a[i].id == c[j]) {
              _selectedIndexList.add(j);
              _selectedCatList.add(j + 1);
              check = true;
              break;
            }
          }
        }
        print(check);
        return _selectedIndexList;
      }

Answered By – user15596782

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.