Flutter保持使用电话号码登录

时间:2020-10-20 10:33:52

标签: firebase flutter authentication

如何注册电话号码并保持登录状态,直到我注销。我正在使用flutter,我已经可以使用电话号码注册用户,但是当重新打开该应用程序时,它将从登录页面开始。

想法是在注册后甚至关闭应用程序后仍保持登录状态。而且我也无法通过圆形指示器显示应用程序正在加载(如果您也向我展示了如何执行此操作,我会非常喜欢的)

这是我的代码。

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

import 'BottomBarPages/home.dart';

class SignIn extends StatefulWidget {
  @override
  _SignInState createState() => _SignInState();
}

class _SignInState extends State<SignIn> {
  TextEditingController phoneController = new TextEditingController();
  String phoneNumber = "";

  bool shower = false;
  String smsCode;
  String verificationCode;

  void _onCountryChange(CountryCode countryCode) {
    this.phoneNumber = countryCode.toString();
    print("New Country selected: " + countryCode.toString());
  }

  void check() {
    final myPhone = this.phoneNumber + phoneController.text;
    print("Full Text: " + myPhone);
  }
  Future<void> man() async{

  }
  Future<void> submit() async {
    final myPhone = this.phoneNumber + phoneController.text;
    final PhoneVerificationCompleted verificationCompleted =
        (AuthCredential credential) {
      setState(() {
        print(credential);
      });
    };
    

    final PhoneVerificationFailed verificationFailed =
        (AuthException exception) {};

    final PhoneCodeSent phoneCodeSent = (String verId, [int forceCodeResend]) {
      this.verificationCode = verId;
      smsCodeDialog(context).then((value) => print("signed"));
    };

    final PhoneCodeAutoRetrievalTimeout autoRetrievalTimeout = (String verId) {
      this.verificationCode = verId;
    };
    await FirebaseAuth.instance.verifyPhoneNumber(
        phoneNumber: myPhone,
        timeout: const Duration(seconds: 5),
        verificationCompleted: verificationCompleted,
        verificationFailed: verificationFailed,
        codeSent: phoneCodeSent,
        codeAutoRetrievalTimeout: autoRetrievalTimeout);
  }

  Future<bool> smsCodeDialog(BuildContext context) {
    return showDialog(
        context: context,
        barrierDismissible: false,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text(
              'Enter Code',
              style: TextStyle(color: Colors.lightGreen, fontSize: 24),
            ),
            content: TextField(
              keyboardType: TextInputType.number,
              onChanged: (Value) {
                smsCode = Value;
              },
            ),
            contentPadding: EdgeInsets.all(10),
            actions: [
              FlatButton(
                  onPressed: () {
                    FirebaseAuth.instance.currentUser().then((user) {
                      if (user != null) {
                        Navigator.of(context).pop();
                        Navigator.push(context,
                            MaterialPageRoute(builder: (context) => Home()));
                      } else {
                        Navigator.of(context).pop();
                        signIn();
                      }
                    });
                  },
                  child: Text(
                    'Verify',
                    style: TextStyle(fontSize: 20, color: Colors.lightGreen),
                  ))
            ],
          );
        });
    // CircularProgressIndicator(
    //   valueColor: new AlwaysStoppedAnimation<Color>(Colors.lightGreen),
    //   value: 0.25,
    // );

  }

  signIn() {
    AuthCredential phoneAuthCredential = PhoneAuthProvider.getCredential(
        verificationId: verificationCode, smsCode: smsCode);
    FirebaseAuth.instance
        .signInWithCredential(phoneAuthCredential)
        .then((user) => Navigator.push(
            context, MaterialPageRoute(builder: (context) => Home())))
        .catchError((e) => print(e));
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScopeNode currentFocus = FocusScope.of(context);

        if (!currentFocus.hasPrimaryFocus) {
          currentFocus.unfocus();
        }
      },
      child: Scaffold(
        body: Column(
          //mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Expanded(
              flex: 1,
              child: Container(
                height: MediaQuery.of(context).size.height,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomRight,
                    stops: [0.1, 0.3, 1.0],
                    colors: [
                      Colors.lightGreen[300],
                      Colors.white,
                      Colors.lightGreen[50]
                    ],
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.symmetric(vertical: 15),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      SizedBox(
                        height: 150,
                        child: Image.asset('images/phone.png'),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 20),
                        child: Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(50),
                              border: Border.all(color: Colors.lightGreen)),
                          width: double.infinity,
                          height: 40,
                          child: Padding(
                            padding: const EdgeInsets.symmetric(horizontal: 30),
                            child: Row(
                             // crossAxisAlignment: CrossAxisAlignment.start,
                              //mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                CountryCodePicker(
                                  dialogTextStyle: TextStyle(fontSize: 20),
                                  onChanged: _onCountryChange,
                                  initialSelection: 'US',
                                  favorite: ['+251', 'ET'],
                                ),
                                Padding(
                                  padding: const EdgeInsets.only(bottom: 10),
                                  child: SizedBox(
                                    width: 150,
                                    child: TextFormField(
                                      controller: phoneController,
                                      keyboardType: TextInputType.phone,
                                      decoration: InputDecoration(
                                        border: InputBorder.none,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      MaterialButton(
                        onPressed: submit,
                        minWidth: MediaQuery.of(context).size.width - 80,
                        height: 45,
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(20)),
                        color: Colors.lightGreen,
                        splashColor: Colors.green,
                        child: Text(
                          "Confirm",
                          style: TextStyle(color: Colors.white, fontSize: 18),
                        ),
                      ),
                      Padding(
                        padding:
                            EdgeInsets.symmetric(vertical: 14, horizontal: 64),
                        child: Text(
                          "you'll receive a 6 digit code click Confirm to verify",
                          textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 22,
                            color: Colors.lightGreen,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

请帮助我。

1 个答案:

答案 0 :(得分:0)

打开应用程序时,请使用以下命令检查用户是否已经登录:

User user = FirebaseAuth.instance.currentUser;

如果用户不为null,则应将应用导航到主屏幕或其他屏幕。尝试以下代码:

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

  getUser() {
    User firebaseUser = FirebaseAuth.instance.currentUser;
    if (firebaseUser != null)
      WidgetsBinding.instance.addPostFrameCallback((_) =>
          Navigator.pushReplacement(
              context, MaterialPageRoute(builder: (context) => HomePage()))); 
  }