如何使用共享首选项让用户保持登录状态

时间:2021-06-15 05:39:24

标签: firebase flutter dart firebase-authentication sharedpreferences

我有一个使用 Firebase 进行授权的扫描应用,我使用共享首选项在关闭应用后让用户保持登录状态,但我收到一条错误消息,提示

The getter 'uid' was called on null. Receiver: null Tried calling: uid

下面是我的 Main.dart 页面

在这个主块中,有一个三元条件应该根据应用程序是刚刚关闭还是退出来确定要转到哪个页面

Future <void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  SharedPreferences preferences = await SharedPreferences.getInstance();
 var email = preferences.get("email");
  await Firebase.initializeApp();
  runApp(MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Jinjer Pay",
      theme: ThemeData(
          primaryColor: Colors.amber,
          visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: email != null ? Login() : Scan_QR()));
     // home: Login()));
}

登录页面代码 我将共享首选项块放在 Auth 的末尾。堵塞。 我不确定我是否使用 Auth 块正确初始化了共享首选项块。

 RaisedButton(
                                  child: Text(
                                    "Log In",
                                    style: TextStyle(fontSize: 19),
                                  ),
                                  color: Colors.amberAccent,
                                  elevation: 10,
                                  shape: RoundedRectangleBorder(
                                      borderRadius:
                                      BorderRadius.circular(15)),
                                  onPressed: () async {
                                    if (formKey.currentState.validate()) {
                                      Loading();
                                      formKey.currentState.save();

                                      setState(() => loading = true);

                                      try {
                                        UserCredential res;
                                        String userID;

                                        res = (await FirebaseAuth.instance
                                            .signInWithEmailAndPassword(
                                            email:
                                            _emailController.text,
                                            password:
                                            _passwordController
                                                .text));
                                        userID = res.user.uid;


                                        if (res != null) {
                                          setState(() {
                                            loading = false;
                                          });
                                          Navigator.pop(context);
                                          Navigator.of(context).push(
                                            MaterialPageRoute(
                                                builder: (context) =>
                                                    Scan_QR()),
                                          );
                                        }
                                      } catch (e) {
                                        if (FirebaseAuth
                                            .instance.currentUser.uid !=
                                            e.code) {
                                          setState(() {
                                            loading = false;
                                          });
                                        }

                                        if (e.code == "unknown") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "Email/Password Field cannot be Empty",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }
                                        if (e.code == "wrong-password") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "Your password is incorrect",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }
                                        if (e.code == "invalid-email") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "Email/Password Field cannot be Empty",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }
                                        if (e.code == "user-not-found") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "No User found with this email",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }
                                        if (e.code == "user-disabled") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "user with this email has been disabled",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }
                                        if (e.code ==
                                            "network-request-failed") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "A network error has occurred",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }
                                        if (e.code == "too-many-requests") {
                                          Fluttertoast.showToast(
                                              msg:
                                              "Too many requests, try again later",
                                              toastLength:
                                              Toast.LENGTH_SHORT,
                                              gravity: ToastGravity.CENTER,
                                              timeInSecForIosWeb: 1,
                                              backgroundColor:
                                              Colors.redAccent,
                                              textColor: Colors.white,
                                              fontSize: 16.0);
                                        }

                                         SharedPreferences preferences = await SharedPreferences.getInstance();
                                         preferences.setString("email", _emailController.text);
                                        Navigator.of(context).push(
                                          MaterialPageRoute(
                                              builder: (context) =>
                                                  Scan_QR()),
                                        );
                                        
                                        print(e);
                                       
                                        _passwordController.text = "";
                                      }

                                      
                                    }
                                  },
                                ),

我有一个注销块,用于从应用注销之前登录的用户数据并等待新用户登录。

Future<void> SignOut() async {
     SharedPreferences preferences = await SharedPreferences.getInstance();
     preferences.remove("email");

   await FirebaseAuth.instance.signOut().then((value) => Navigator.of(context)
       .push(MaterialPageRoute(builder: (context) => Login())));

  }

1 个答案:

答案 0 :(得分:1)

您可以在打开应用程序时使用 StreamBuilder 来检查身份验证过程,而不是使用共享首选项。

FirebaseAuth mAuth = FirebaseAuth.instance;
@override
Widget build(BuildContext context) {
    return StreamBuilder<FirebaseUser>(
        stream: mAuth.onAuthStateChanged,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.active) {
            FirebaseUser user = snapshot.data;
            if (user == null) {
              //add the logic when user is null
            } else {
              // add the logic when user is not null
            }
            
          } else {
            // add the logic when connection state not active
          }
        },
    );
  }

然后您可以在不使用共享首选项的情况下进行身份验证。

希望这个答案能解决您的问题!