首页 > 解决方案 > 如何在flutter中使用firebase通过电话身份验证检查用户是否登录?

问题描述

在这里,我使用 Firebase 通过带有 OTP 代码的电话号码进行了身份验证,但登录成功后,它浏览了主页,但是当我点击返回时,它拖着我的登录屏幕。

在这里,我尝试过的代码,但它不起作用

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


  void isSignedIn() async {
    this.setState(() {
      isLoading = true;
    });

  firebaseAuth.currentUser().then((user){
    if(user !=null){
      Navigator.of(context).pushReplacementNamed('/homepage');
    }else{
       verifyPhone();
    }
  });
  this.setState(() {
    isLoading = false;
  });

  }

获取OTP码的方法

Future<void> verifyPhone()async{
    final PhoneCodeAutoRetrievalTimeout autoRetrieval=(String verId){
      this.verificationId=verId;
    };

    final PhoneCodeSent smsCodeSent=(String verId, [int forceCodeResend]){
      this.verificationId=verId;
      smsCodeDialog(context).then((value){
        print("Signed in");
      });
    };



    final PhoneVerificationCompleted verificationCompleted = (AuthCredential credential) {
     print("verified");
   };

    final PhoneVerificationFailed verfifailed=(AuthException exception){
      print("${exception.message}");
    };

    await firebaseAuth.verifyPhoneNumber(
     phoneNumber: this.phoneNo,
     codeAutoRetrievalTimeout: autoRetrieval,
     codeSent: smsCodeSent,
     timeout: const Duration(seconds: 10),
     verificationCompleted: verificationCompleted,
     verificationFailed: verfifailed
    );
  }

这里是使用 OTP 代码登录的对话框

Future<bool> smsCodeDialog(BuildContext context){
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context){
        return new AlertDialog(
          title: Text('Enter sms Code'),
          content: TextField(
            onChanged: (value){
              this.smsCode=value;
            },
          ),
          contentPadding: const EdgeInsets.all(10.0),
          actions: <Widget>[
            new FlatButton(
              child: Text("Done"),
              onPressed: (){
                firebaseAuth.currentUser().then((user){
                  if(user !=null){
                    Navigator.of(context).pop();
                    Navigator.of(context).pushReplacementNamed('/homepage');
                  }else{
                    Navigator.of(context).pop();
                    signIn();
                  }
                });
              },
            )
          ],
        );
      }
    );
  }

手机号登录方法

signIn()async{
    AuthCredential credential= PhoneAuthProvider.getCredential(
      verificationId: verificationId,
      smsCode: smsCode
    );
    await  firebaseAuth.signInWithCredential(credential).then((user){
       Navigator.of(context).pushReplacementNamed('/homepage');
         print('signed in with phone number successful: user -> $user');
    }).catchError((onError){
      print(onError);
    });
  }
`

标签: flutterdartfirebase-authentication

解决方案


欢迎使用 Stackoverflow 和 Flutter 开发人员的Shruti Ramnandan Sharma

您的代码似乎对我很好,我为您编写了一个单页飞镖,它可以测试您的整个代码,解决您返回登录或验证电话页面的问题。

注意:我在方法中更改了您的代码顺序verifyPhone()

Navigator.of(context).pushReplacementNamed('/homepage');改为

Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => HomeRoute()));

整个代码在这里

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

void main() => runApp(VerifyPhoneRoute());

class VerifyPhoneRoute extends StatefulWidget {
  @override
  _VerifyPhoneRouteState createState() {
    return _VerifyPhoneRouteState();
  }
}

class _VerifyPhoneRouteState extends State<VerifyPhoneRoute> {
  bool isLoading = false;
  FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  String verificationId;
  String phoneNo = "Your number here";
  String smsCode;

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

  void isSignedIn() async {
    this.setState(() {
      isLoading = true;
    });

    firebaseAuth.currentUser().then((user) {
      if (user != null) {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => HomeRoute()),
        );
      } else {
        verifyPhone();
      }
    });
    this.setState(() {
      isLoading = false;
    });
  }

  Future<void> verifyPhone() async {
    final PhoneVerificationCompleted verificationCompleted =
        (AuthCredential credential) {
      print("verified");
    };

    final PhoneVerificationFailed verifyFailed = (AuthException exception) {
      print("${exception.message}");
    };

    final PhoneCodeSent smsCodeSent = (String verId, [int forceCodeResend]) {
      this.verificationId = verId;
      smsCodeDialog(context).then((value) {
        print("Signed in");
      });
    };

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

    await firebaseAuth.verifyPhoneNumber(
        phoneNumber: this.phoneNo,
        codeAutoRetrievalTimeout: autoRetrieval,
        codeSent: smsCodeSent,
        timeout: const Duration(seconds: 10),
        verificationCompleted: verificationCompleted,
        verificationFailed: verifyFailed);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Inapp Plugin by dooboolab'),
        ),
        body: Center(
          child: RaisedButton(
              child: Text("Verify"),
              onPressed: () {
                verifyPhone();
              }),
        ),
      ),
    );
  }

  Future<bool> smsCodeDialog(BuildContext context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return new AlertDialog(
            title: Text('Enter sms Code'),
            content: TextField(
              onChanged: (value) {
                this.smsCode = value;
              },
            ),
            contentPadding: const EdgeInsets.all(10.0),
            actions: <Widget>[
              new FlatButton(
                child: Text("Done"),
                onPressed: () {
                  firebaseAuth.currentUser().then((user) {
                    if (user != null) {
                      Navigator.of(context).pop();
                      Navigator.pushReplacement(
                        context,
                        MaterialPageRoute(builder: (context) => HomeRoute()),
                      );
                    } else {
                      Navigator.of(context).pop();
                      signIn();
                    }
                  });
                },
              )
            ],
          );
        });
  }

  signIn() async {
    AuthCredential credential = PhoneAuthProvider.getCredential(
        verificationId: verificationId, smsCode: smsCode);
    await firebaseAuth.signInWithCredential(credential).then((user) {
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => HomeRoute()),
      );
      print('signed in with phone number successful: user -> $user');
    }).catchError((onError) {
      print(onError);
    });
  }
}

class HomeRoute extends StatefulWidget {
  @override
  _HomeRouteState createState() {
    return _HomeRouteState();
  }
}

class _HomeRouteState extends State<HomeRoute> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Inapp Plugin by dooboolab'),
        ),
        body: Center(
          child: Text("Welcome There."),
        ),
      ),
    );
  }
}

这段代码适用于我。因此,如果您再次遇到任何问题,请随时对此答案发表评论。如果这回答了您的问题并解决了您的问题,请将其作为答案。


推荐阅读