简体   繁体   中英

Could not find the correct provider in flutter application

I am trying to execute the phone authentication for the flutter application using firebae authentication. But I am getting Pop Up message for Error: Could not find the correct Provider<AuthProvider> for the authentication widget. I am trying to resolve this issue but could not get to the point as of now.

I am learning these new things

Here is the Scaffold code for the page used.

Scaffold(
      backgroundColor: Colors.white,

      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Align(
                //     alignment: Alignment.centerLeft,
                //     child: Padding(
                //       padding: const EdgeInsets.all(10.0),
                //       child: Text(
                //         'PickUp',
                //         style: Theme.of(context).textTheme.headline6,
                //       ),
                //     )),
                Container(
                  height: 340,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage('assets/images/background.png'),
                          fit: BoxFit.fill
                      )
                  ),
                  child: Stack(
                    children: <Widget>[
                      Positioned(
                        left: 30,
                        width: 80,
                        height: 150,
                        child: FadeAnimation(1, Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('assets/images/light-1.png')
                              )
                          ),
                        )),
                      ),
                      Positioned(
                        left: 140,
                        width: 80,
                        height: 150,
                        child: FadeAnimation(1.3, Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('assets/images/light-2.png')
                              )
                          ),
                        )),
                      ),
                      Positioned(
                        right: 40,
                        top: 40,
                        width: 80,
                        height: 150,
                        child: FadeAnimation(1.5, Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('assets/images/clock.png')
                              )
                          ),
                        )),
                      ),
                      Positioned(
                        child: FadeAnimation(1.6, Container(
                          margin: EdgeInsets.only(top: 50),
                          child: Center(
                            child: Text("The Nandy Club", style: TextStyle(color: Colors.white, fontSize: 40, fontWeight: FontWeight.bold),),
                          ),
                        )),
                      )
                    ],
                  ),
                ),
                Align(
                    alignment: Alignment.center,
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(
                        'Please enter your number below',
                        style: Theme.of(context).textTheme.headline6,
                      ),
                    )),


                Container(
                  height: 50,
                  width: 200,
                  decoration: BoxDecoration(

                    border: Border.all(color: Colors.blueAccent),
                      borderRadius: BorderRadius.circular(10),
                      // gradient: LinearGradient(
                      //     colors: [
                      //       Color.fromRGBO(143, 148, 251, 1),
                      //       Color.fromRGBO(143, 148, 251, .6),
                      //     ]
                      // )
                  ),
                  child: CountryCodePicker(
                    initialSelection: selectedCountryCode,
                    onChanged: _onCountryChange,
                    showCountryOnly: false,
                    showOnlyCountryWhenClosed: false,
                  ),
                ),
                SizedBox(width: 2,),
                UserTextField(
                  titleLabel: 'Enter your number',
                  maxLength: 10,
                  icon: Icons.smartphone,
                  controller: controller,
                  inputType: TextInputType.phone,
                ),

                Align(
                  alignment: Alignment.center,
                  child: GestureDetector(
                    onTap: (){

                      print(controller.text);
                      verifyPhone(context);
                    },
                    child: Container(
                      height: 50,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          gradient: LinearGradient(
                              colors: [
                                Color.fromRGBO(143, 148, 251, 1),
                                Color.fromRGBO(143, 148, 251, .6),
                              ]
                          )
                      ),
                      child: Center(
                        child: Text(

                           'Send OTP',

                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

The code for verifyPhone method

verifyPhone(BuildContext context){

    print(controller.text);
    print(selectedCountryCode);
    try {
      Provider.of<AuthProvider>(context, listen: false)
          .verifyPhone(
          selectedCountryCode,
          selectedCountryCode +
              controller.text.toString())
          .then((value) {
        Navigator.of(context)
            .pushNamed(VerifyScreen.routeArgs);
      }).catchError((e) {
        String errorMsg =
            'Cant Authenticate you, Try Again Later';
        if (e.toString().contains(
            'We have blocked all requests from this device due to unusual activity. Try again later.')) {
          errorMsg =
          'Please wait as you have used limited number request';
        }
        _showErrorDialog(context, errorMsg);
      });
    } catch (e) {
      _showErrorDialog(context, e.toString());
    }
  }

Upon tapping the Send OTP the method is called but it shows the popup error message on the screen of the simulator but no error message is in the console.

Please guide me how to resolve it, if any more code information is required please let me know

Screenshot of the error message Error Message On The Screen

The AuthProvider Class Created is Here Below for the above code query

class AuthProvider with ChangeNotifier {
  final _firebaseAuth = FirebaseAuth.instance;
  String verificationId;

  Future<void> verifyPhone(String countryCode, String mobile) async {
    var mobileToSend = mobile;
    final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
      this.verificationId = verId;
    };
    try {
      await _firebaseAuth.verifyPhoneNumber(
          phoneNumber: mobileToSend,
          codeAutoRetrievalTimeout: (String verId) {
            //Starts the phone number verification process for the given phone number.
            //Either sends an SMS with a 6 digit code to the phone number specified, or sign's the user in and [verificationCompleted] is called.
            this.verificationId = verId;
          },
          codeSent: smsOTPSent,
          timeout: const Duration(
            seconds: 120,
          ),
          verificationCompleted: (AuthCredential phoneAuthCredential) {
            print(phoneAuthCredential);
          },
          verificationFailed: ( exception) {
            throw exception;
          });
    } catch (e) {
      throw e;
    }
  }

  Future<void> verifyOTP(String otp) async {
    try {
      final AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: otp,
      );
      final UserCredential user =
          await _firebaseAuth.signInWithCredential(credential);
      final User currentUser = await _firebaseAuth.currentUser;
      print(user);

      if (currentUser.uid != "") {
        print(currentUser.uid);
      }
    } catch (e) {
      throw e;
    }
  }

  showError(error) {
    throw error.toString();
  }
}

I am trying to execute the phone authentication for the flutter application using firebae authentication. But I am getting Pop Up message for Error: Could not find the correct Provider<AuthProvider> for the authentication widget. I am trying to resolve this issue but could not get to the point as of now.

I am learning these new things

Here is the Scaffold code for the page used.

Scaffold(
      backgroundColor: Colors.white,

      body: SafeArea(
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                // Align(
                //     alignment: Alignment.centerLeft,
                //     child: Padding(
                //       padding: const EdgeInsets.all(10.0),
                //       child: Text(
                //         'PickUp',
                //         style: Theme.of(context).textTheme.headline6,
                //       ),
                //     )),
                Container(
                  height: 340,
                  decoration: BoxDecoration(
                      image: DecorationImage(
                          image: AssetImage('assets/images/background.png'),
                          fit: BoxFit.fill
                      )
                  ),
                  child: Stack(
                    children: <Widget>[
                      Positioned(
                        left: 30,
                        width: 80,
                        height: 150,
                        child: FadeAnimation(1, Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('assets/images/light-1.png')
                              )
                          ),
                        )),
                      ),
                      Positioned(
                        left: 140,
                        width: 80,
                        height: 150,
                        child: FadeAnimation(1.3, Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('assets/images/light-2.png')
                              )
                          ),
                        )),
                      ),
                      Positioned(
                        right: 40,
                        top: 40,
                        width: 80,
                        height: 150,
                        child: FadeAnimation(1.5, Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: AssetImage('assets/images/clock.png')
                              )
                          ),
                        )),
                      ),
                      Positioned(
                        child: FadeAnimation(1.6, Container(
                          margin: EdgeInsets.only(top: 50),
                          child: Center(
                            child: Text("The Nandy Club", style: TextStyle(color: Colors.white, fontSize: 40, fontWeight: FontWeight.bold),),
                          ),
                        )),
                      )
                    ],
                  ),
                ),
                Align(
                    alignment: Alignment.center,
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(
                        'Please enter your number below',
                        style: Theme.of(context).textTheme.headline6,
                      ),
                    )),


                Container(
                  height: 50,
                  width: 200,
                  decoration: BoxDecoration(

                    border: Border.all(color: Colors.blueAccent),
                      borderRadius: BorderRadius.circular(10),
                      // gradient: LinearGradient(
                      //     colors: [
                      //       Color.fromRGBO(143, 148, 251, 1),
                      //       Color.fromRGBO(143, 148, 251, .6),
                      //     ]
                      // )
                  ),
                  child: CountryCodePicker(
                    initialSelection: selectedCountryCode,
                    onChanged: _onCountryChange,
                    showCountryOnly: false,
                    showOnlyCountryWhenClosed: false,
                  ),
                ),
                SizedBox(width: 2,),
                UserTextField(
                  titleLabel: 'Enter your number',
                  maxLength: 10,
                  icon: Icons.smartphone,
                  controller: controller,
                  inputType: TextInputType.phone,
                ),

                Align(
                  alignment: Alignment.center,
                  child: GestureDetector(
                    onTap: (){

                      print(controller.text);
                      verifyPhone(context);
                    },
                    child: Container(
                      height: 50,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          gradient: LinearGradient(
                              colors: [
                                Color.fromRGBO(143, 148, 251, 1),
                                Color.fromRGBO(143, 148, 251, .6),
                              ]
                          )
                      ),
                      child: Center(
                        child: Text(

                           'Send OTP',

                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );

The code for verifyPhone method

verifyPhone(BuildContext context){

    print(controller.text);
    print(selectedCountryCode);
    try {
      Provider.of<AuthProvider>(context, listen: false)
          .verifyPhone(
          selectedCountryCode,
          selectedCountryCode +
              controller.text.toString())
          .then((value) {
        Navigator.of(context)
            .pushNamed(VerifyScreen.routeArgs);
      }).catchError((e) {
        String errorMsg =
            'Cant Authenticate you, Try Again Later';
        if (e.toString().contains(
            'We have blocked all requests from this device due to unusual activity. Try again later.')) {
          errorMsg =
          'Please wait as you have used limited number request';
        }
        _showErrorDialog(context, errorMsg);
      });
    } catch (e) {
      _showErrorDialog(context, e.toString());
    }
  }

Upon tapping the Send OTP the method is called but it shows the popup error message on the screen of the simulator but no error message is in the console.

Please guide me how to resolve it, if any more code information is required please let me know

Screenshot of the error message Error Message On The Screen

The AuthProvider Class Created is Here Below for the above code query

class AuthProvider with ChangeNotifier {
  final _firebaseAuth = FirebaseAuth.instance;
  String verificationId;

  Future<void> verifyPhone(String countryCode, String mobile) async {
    var mobileToSend = mobile;
    final PhoneCodeSent smsOTPSent = (String verId, [int forceCodeResend]) {
      this.verificationId = verId;
    };
    try {
      await _firebaseAuth.verifyPhoneNumber(
          phoneNumber: mobileToSend,
          codeAutoRetrievalTimeout: (String verId) {
            //Starts the phone number verification process for the given phone number.
            //Either sends an SMS with a 6 digit code to the phone number specified, or sign's the user in and [verificationCompleted] is called.
            this.verificationId = verId;
          },
          codeSent: smsOTPSent,
          timeout: const Duration(
            seconds: 120,
          ),
          verificationCompleted: (AuthCredential phoneAuthCredential) {
            print(phoneAuthCredential);
          },
          verificationFailed: ( exception) {
            throw exception;
          });
    } catch (e) {
      throw e;
    }
  }

  Future<void> verifyOTP(String otp) async {
    try {
      final AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId,
        smsCode: otp,
      );
      final UserCredential user =
          await _firebaseAuth.signInWithCredential(credential);
      final User currentUser = await _firebaseAuth.currentUser;
      print(user);

      if (currentUser.uid != "") {
        print(currentUser.uid);
      }
    } catch (e) {
      throw e;
    }
  }

  showError(error) {
    throw error.toString();
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM