flutter firebase sms verification example

Example: auto navigate to home screen after otp login flutter

class SignUpView extends StatefulWidget {
  
  _SignUpViewState createState() => _SignUpViewState();
}

class _SignUpViewState extends State<SignUpView> {

  final formKey = new GlobalKey<FormState>();

  String phoneNo, verificationId, smsCode;

  bool codeSent = false;

  
  Widget build(BuildContext context) {
    return Scaffold(
      body: Form(
        key: formKey,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(left: 25, right: 25),
              child: TextFormField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(hintText: "Enter Phone Number"),

                onChanged: (val) {
                  setState(() {
                    this.phoneNo = val;
                  });
                },
              ),
            ),


           codeSent ? Padding(
              padding: EdgeInsets.only(left: 25, right: 25),
              child: TextFormField(
                keyboardType: TextInputType.phone,
                decoration: InputDecoration(hintText: "Enter OTP"),

                onChanged: (val) {
                  setState(() {
                    this.smsCode = val;
                  });
                },
              ),
           ): Container(),




            Padding(
              padding: EdgeInsets.only(left: 25, right: 25),
              child: RaisedButton(
                child: Center(
                  child: codeSent ? Text("Login") : Text("Login"),
                ),
                onPressed: () {
                  codeSent? AuthService().signInWithOTP(smsCode, verificationId):verifyPhone(phoneNo);
                  },
              ),
            ),

          ],
        ),
      ),
    );
  }

  Future<void> verifyPhone(phoneNo) async {
    final PhoneVerificationCompleted verified = (AuthCredential authResult) {
      AuthService().signIn(authResult);
    };

    final PhoneVerificationFailed verificationFailed = (
        AuthException authException) {
      print('${authException.message}');
    };

    final PhoneCodeSent smsSent = (String verId, [int forceResend]) {
      this.verificationId = verId;
      setState(() {
        this.codeSent = true;
      });
    };

    final PhoneCodeAutoRetrievalTimeout autoTimeOut = (String verId) {
      this.verificationId = verId;
    };


    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: phoneNo,
        timeout: const Duration(seconds: 5),
        verificationCompleted: verified,
        verificationFailed: verificationFailed,
        codeSent: smsSent,
        codeAutoRetrievalTimeout: autoTimeOut);
  }
}

Tags:

Dart Example