flutterproviderconsumer

Replacing Widget in Flutter with use of Provider


I am using Provider state management in my Flutter app project. Actually, Its OTP screen which is divided in to to Widget:

  1. Enter Phone Number Widget,
  2. Enter OTP widget.

I can't replace my second widget once user enteres Phone number and click on 'Send' button. Below is my OTP Screen you can check:

Expanded(
child: Consumer(
    builder: (BuildContext context, value, Widget? child) {
    return ResponsiveHelperWidget(
        mobile: viewModel.isPhoneNumberEntered
            ? fillPhoneNumberWidget
            : otpVerificationWidget,
        desktop: Row(
        children: [
            const Expanded(child: OTPWebPageFillerWidget()),
            Expanded(child: fillPhoneNumberWidget),
        ],
        ),
    );
    },
),
)

Here, you can check this line:

viewModel.isPhoneNumberEntered
                    ? fillPhoneNumberWidget
                    : otpVerificationWidget,

That is the way I am trying to replace my widget.

You can check my ViewModel as below:

class OTPViewModel extends ChangeNotifier {
    http.Client client = http.Client();
    var isPhoneNumberEntered = false;
    OTPViewModel() {
    //pending..
    }
      
    final TextEditingController phoneC = TextEditingController();
    final TextEditingController otpC = TextEditingController();
      
    set setPhoneNumberEntered(bool value) {
    isPhoneNumberEntered = value;
    notifyListeners();
    }
}

Here you can check the setter setPhoneNumberEntered where I am changing the value and notifying the listener.

Calling this setter as below in my first widget as below:

onPressed: () {                                     
    widget.viewModel.setPhoneNumberEntered = true;
                },

But the issue is my second widget (Enter OTP Widget) is not being visible.

What I am doing wrong here? Please guide.


Solution

  • It was just a silly mistake:

    Have to replace this:

    desktop: Row(
              children: [
                const Expanded(child: OTPWebPageFillerWidget()),
                Expanded(child: fillPhoneNumberWidget),
              ],
            ),
    

    with this:

    desktop: Row(
                    children: [
                      const Expanded(child: OTPWebPageFillerWidget()),
                      Expanded(
                          child: value.isPhoneNumberEntered
                              ? otpVerificationWidget
                              : fillPhoneNumberWidget),
                    ],
                  ),