Home > OS >  Value of Provider is not resetting when popping away and coming back
Value of Provider is not resetting when popping away and coming back

Time:01-27

Provider file

class TermsOfServiceProvider extends ChangeNotifier {
  bool _termsOfService = false;

  bool get termsOfService => _termsOfService;

  void termsOfServiceUpdated(bool value) {
    _termsOfService = value;

    notifyListeners();
  }
}

Above is the provider I am using.

CheckoutButton(
                  onPressed:
                      context.watch<TermsOfServiceProvider>().termsOfService
                          ? () {
                              orderAddressBloc.handleFormSubmit(
                                addressFormValues!.value,
                                customerInfoFormValues!.value,
                                useAsBilling: useAsBillingValue.value,
                                optedIn: optIn.value,
                                termsAndConditions: termsConditions.value,
                              );
                            }
                          : null,
                  blocLoadingIndicator: orderAddressBloc.loadingIndicator,
                ),

Above is where I am using the value.

But when I'm popping away from this page and returning the value of termsOfService when coming back is not changing.

I am using a checkbox for handling the data validation so when it is true it is activating a button to be clicked and false the button is inactive.

But when I am clicking for it to be true and navigating away and coming back the checkbox is not ticked but the value is true, setting the button to active when it shouldn't be.

  child: CheckboxListTile(
    value: checkedValue,
    onChanged: (bool? newValue) {
      context
          .read<TermsOfServiceProvider>()
          .termsOfServiceUpdated(newValue!);
      setState(() {
        checkedValue = newValue;
      });
    },

Above is the checkbox code.

CodePudding user response:

You are not properly resetting the value of _termsOfService when navigating away and returning to the page. you can fix it by using the didChangeDependencies method in your CheckoutButton widget to reset the value of _termsOfService when the widget is rebuilt.

@override
void didChangeDependencies() {
    super.didChangeDependencies();
    final provider = Provider.of<TermsOfServiceProvid(context,listen:false);
    provider._termsOfService = false;
}

This will reset the value of _termsOfService to false when the widget is rebuilt, so the checkbox will be unticked and the button will be inactive when the user navigates back to the page.

  • Related