Firebase电话身份验证无法正常工作

时间:2020-07-20 06:11:47

标签: firebase android-studio flutter dart firebase-authentication

我正在开发一个使用flutter的应用程序,该应用程序使用Firebase进行电话身份验证。 这是我的代码:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'home_screen.dart';

class LoginScreen extends StatefulWidget {
  @override
  _LoginScreenState createState() => _LoginScreenState();
}

class _LoginScreenState extends State<LoginScreen> {
  TextEditingController phoneController = new TextEditingController();
  String smsCode;
  String verificationCode;

  Future<void> alert() async {
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // user must tap button!
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Wrong OTP !'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text('The otp you entered is wrong'),
                Text('If the issue persists, please try again later.'),
              ],
            ),
          ),
          actions: <Widget>[
            FlatButton(
              child: Text('Close'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        child: SingleChildScrollView(
          child: Column(
            children: <Widget>[
              Padding(
                padding: EdgeInsets.only(top: 150.0, bottom: 32.0),
                child: Image(
                  image: AssetImage('images/login.png'),
                  height: 128.0,
                ),
              ),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: TextField(
                  controller: phoneController,
//                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                      contentPadding:
                          EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                      hintText: "Phone Number",
                      border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(16.0))),
                ),
              ),
              //    Checkbox(),
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: RaisedButton(
                  color: Colors.white,
                  elevation: 10,
                  shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10.0),
                      side: BorderSide(color: Colors.teal)),
                  onPressed: () async {
                    print(phoneController.text);
                    try {
                      _submit();
                    } catch (e) {
                      alert();
                    }
                  },
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Text(
                      'Send OTP',
                      style: TextStyle(fontSize: 24.0),
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Future<void> _submit() async {
    print('Submitted');
    final PhoneVerificationCompleted verificationSuccess =
        (AuthCredential credential) {
      setState(() {
        print('Verification');
        print(credential);
      });
    };

    final PhoneVerificationFailed verificationFailed =
        (AuthException exception) {
      print('Failed');
      print(exception.message);
    };

    final PhoneCodeSent phoneCodeSent = (String verId, [int forceCodeResend]) {
      verificationCode = verId;
      smsDialogBox(context).then((value) => print('Signed In'));
    };
    final PhoneCodeAutoRetrievalTimeout phoneCodeAutoRetrievalTimeout =
        (String verId) {
      verificationCode = verId;
    };
    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: '+91${phoneController.text}',
        timeout: Duration(minutes: 1),
        verificationCompleted: verificationSuccess,
        verificationFailed: verificationFailed,
        codeSent: phoneCodeSent,
        codeAutoRetrievalTimeout: phoneCodeAutoRetrievalTimeout);
  }

  Future<bool> smsDialogBox(BuildContext context) {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return AlertDialog(
          title: Text(
            'Enter OTP',
            style: TextStyle(
              color: Colors.lightBlueAccent,
            ),
          ),
          content: TextField(
            keyboardType: TextInputType.number,
            onChanged: (value) {
              smsCode = value;
            },
            decoration: InputDecoration(
                contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
                hintText: "Enter received otp",
                border: OutlineInputBorder(
                    borderRadius: BorderRadius.circular(16.0))),
          ),
          contentPadding: EdgeInsets.all(10),
          actions: <Widget>[
            FlatButton(
              onPressed: () {
                FirebaseAuth.instance.currentUser().then((user) {
                  if (user != null) {
                    Navigator.of(context).pop();
                    var message = Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => HomeScreen(
                          phoneNumber: phoneController.text,
                        ),
                      ),
                    );
                  } else {
                    Navigator.pop(context);
                    signIn();
                  }
                });
              },
              child: Text(
                'Verify',
                style: TextStyle(
                  color: Colors.lightBlueAccent,
                ),
              ),
            ),
          ],
        );
      },
    );
  }

  signIn() {
    AuthCredential authCredential = PhoneAuthProvider.getCredential(
        verificationId: verificationCode, smsCode: smsCode);
    FirebaseAuth.instance
        .signInWithCredential(authCredential)
        .then(
          (user) => Navigator.push(
            context,
            MaterialPageRoute(
              builder: (context) => HomeScreen(
                phoneNumber: phoneController.text,
              ),
            ),
          ),
        )
        .catchError((e) => alert());
  }
}

但是,身份验证现在不起作用。不管输入的OTP是正确还是错误,都会显示警告消息,并继续进入主屏幕。

任何指导将不胜感激。预先感谢。

PS:昨天好像工作正常。

0 个答案:

没有答案