Flutter 电话身份验证崩溃

时间:2021-03-04 17:37:38

标签: firebase flutter authentication firebase-authentication

我已经在 main.dart 文件中初始化了 firebase。我还导入了所有必要的数据包,以使我的应用程序与 firebase 连接,但最初我没有收到 OTP。经过大量搜索我读到有必要将SHA-1和SHA-256指纹添加到项目中,所以我做了同样的事情。现在,即使没有收到 OTP,只要推送 OTP 屏幕,应用就会崩溃。

<块引用>

otp_screen.dart

import 'package:ambur/app_content/widgets/custom_bottom_navigation_bar.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:flutter_svg/svg.dart';

import '../widgets/custom_signin_button.dart';
import '../widgets/user_input_field.dart';
import '../../constants.dart';

class OTPScreen extends StatefulWidget {
  final String mobileNumber;
  OTPScreen(this.mobileNumber);
  @override
  _OTPScreenState createState() => _OTPScreenState();
}

class _OTPScreenState extends State<OTPScreen> {
  final _otpController = TextEditingController();
  final GlobalKey<ScaffoldState> _scaffoldkey = GlobalKey<ScaffoldState>();
  final FirebaseAuth auth = FirebaseAuth.instance;
  String _verificationCode;

  @override
  void initState() {
    super.initState();
    _verifyPhone();
  }

  _verifyPhone() async {
    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: '+91${widget.mobileNumber}',
        verificationCompleted: (PhoneAuthCredential credential) async {
          await auth.signInWithCredential(credential).then((value) async {
            if (value.user != null) {
              Navigator.pushAndRemoveUntil(
                  context,
                  MaterialPageRoute(
                      builder: (context) => CustomBottomNavigationBar()),
                  (route) => false);
            }
          });
        },
        verificationFailed: (FirebaseAuthException e) {
          print(e.message);
        },
        codeSent: (String verficationID, int resendToken) {
          setState(() {
            _verificationCode = verficationID;
          });
        },
        codeAutoRetrievalTimeout: (String verificationID) {
          setState(() {
            _verificationCode = verificationID;
          });
        },
        timeout: Duration(seconds: 120));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: _scaffoldkey,
      appBar: AppBar(title: Text('Verification')),
      resizeToAvoidBottomPadding: false,
      backgroundColor: kBackgroundColor,
      body: Padding(
        padding: const EdgeInsets.all(20.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            SvgPicture.asset(
              'assets/images/otp.svg',
              height: 175,
            ),
            const SizedBox(height: 20),
            const Text(
              'Enter One Time Passoword',
              style: kLoginHeadingTextStyle,
            ),
            const SizedBox(height: 10),
            const Text(
              'An OTP has sent to your mobile number',
              style: kLoginSubHeadingTextStyle,
            ),
            const SizedBox(height: 15),
            UserInputField(
              icon: Icons.lock,
              labelText: 'OTP',
              maxLength: 6,
              keyboardType: TextInputType.number,
              controller: _otpController,
              floatingLabelBehavior: FloatingLabelBehavior.never,
            ),
            const SizedBox(height: 15),
            CustomSignInButton(
              title: 'Validate OTP',
              onPressed: () async {
                try {
                  await auth
                      .signInWithCredential(PhoneAuthProvider.credential(
                          verificationId: _verificationCode,
                          smsCode: _otpController.text))
                      .then((value) async {
                    if (value.user != null) {
                      Navigator.pushAndRemoveUntil(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  CustomBottomNavigationBar()),
                          (route) => false);
                    }
                  });
                } catch (e) {
                  FocusScope.of(context).unfocus();
                  _scaffoldkey.currentState.showSnackBar(SnackBar(
                    duration: const Duration(seconds: 1),
                    backgroundColor: Theme.of(context).primaryColor,
                    content: Center(child: const Text('Invalid OTP')),
                  ));
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

1 个答案:

答案 0 :(得分:0)

在这种情况下,问题可能是 Firebase 的初始化不正确。

如果这是真的,修复它的最佳步骤是

  1. 根据 flutter fire docs
  2. 检查 pubspec.yaml 中的软件包版本是否正确和最新
  3. 通过从 Firebase 控制台下载最新版本来替换项目中的 google-services.json 文件
  4. 正确安装文件 (instructions)。
  5. 启用 Multidex (instructions)。