Search code examples
flutterdartriverpod

Updating a notifier while the widget tree is still being built


I am trying to update a notifier in the initState function but I am getting an error:

FlutterError (Tried to modify a provider while the widget tree was building

Then it gives the suggestion to do this:

Delay your modification, such as by encasuplating the modification in a Future(() {...}).

I am not sure how to do this. I looked at the FutureProvider documentation but I'm not sure that is what I want.

I have a ConsumerStatefulWidget class that I am working with. All the code is inside the ConsumerState class. Here is the code I am working with:

getCurrentCompanyProfile() async {
    if (ref.read(globalsNotifierProvider).companyId == null ||
        ref.read(globalsNotifierProvider).companyId == "") {
      ref.read(globalsNotifierProvider.notifier).updatenewCompany(true);  <<< ERROR HERE
      agencyNameController.text = "";
      address1Controller.text = "";
      address2Controller.text = "";
      cityController.text = "";
      stateController.text = "";
      zipController.text = "";
      cellPhoneController.text = "";
      officePhoneController.text = "";
      emailController.text = "";
      websiteController.text = "";
    } else {
      final DocumentSnapshot currentAgencyProfile = await companyRef
          .doc(ref.read(globalsNotifierProvider).companyId)
          .get();

      // existing record
      // Updates Controllers
      agencyNameController.text = currentAgencyProfile["name"] ?? "";
      address1Controller.text = currentAgencyProfile['address1'] ?? "";
      address2Controller.text = currentAgencyProfile['address2'] ?? "";
      cityController.text = currentAgencyProfile['city'] ?? "";
      stateController.text = currentAgencyProfile['state'] ?? "";
      _currentCompanyState = currentAgencyProfile['state'] ?? "";
      zipController.text = currentAgencyProfile['zipCode'].toString() ?? "";
      cellPhoneController.text = currentAgencyProfile['cellPhone'] ?? "";
      officePhoneController.text = currentAgencyProfile['officePhone'] ?? "";
      emailController.text = currentAgencyProfile['email'] ?? "";
      websiteController.text = currentAgencyProfile['website'] ?? "";

    }
  }

This is where I am calling the getCurrentCompanyProfile:

@override
  void initState() {
    getCurrentCompanyProfile();
    super.initState();

    _dropDownState = getDropDownState();
    _currentCompanyState = _dropDownState[0].value;
  }

How do I get this to update the notifier after the widget tree has been built?

Thanks


Solution

  • As a quick fix, you can put your modification inside this callback:

    @override
    void initState() {
      // ...
    
      WidgetsBinding.instance.addPostFrameCallback((_) {
        getCurrentCompanyProfile();
      });
    }