【问题标题】:flutter & firebase| I'm trying to show a snackBar for the users who doesn't have an account but it show in my terminal'[firebase_auth/user-not-found]'颤振和火力|我正在尝试为没有帐户的用户显示一个snackBar,但它显示在我的终端“[firebase_auth/user-not-found]”中
【发布时间】:2021-10-16 04:32:17
【问题描述】:

我在登录页面上创建了两种身份验证,一种用于验证,另一种用于检查用户之前是否注册过(如果他们有帐户)。我的问题是当用户之前没有注册并且他们尝试登录时,他们应该看到一个 SnackBar 说“电子邮件或密码不正确”但它不起作用并且它显示在终端“未处理的异常:[firebase_auth /user-not-found] 没有与此标识符对应的用户记录。该用户可能已被删除。"

枚举:

enum ViewState { Ideal, Busy }
enum AuthState { SignIn, SignUp }

AuthModel:

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:gray_green/enum/appState.dart';

import 'baseModel.dart';

BuildContext ctx;
// User currentUser = FirebaseAuth.instance.currentUser;

//UserCredential userCredential;

class AuthModel extends BaseModel {
  FirebaseAuth firebaseAuth = FirebaseAuth.instance;
  void createNewUser(String email, String password) async {
    setViewState(ViewState.Busy);
    await firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password);
    setViewState(ViewState.Ideal);
  }

  void signIn(String email, String password) async {
    setViewState(ViewState.Busy);
    await firebaseAuth.signInWithEmailAndPassword(
        email: email, password: password);
    setViewState(ViewState.Ideal);

  }

  void logOut() async {
    setViewState(ViewState.Busy);
    await firebaseAuth.signOut();
    setViewState(ViewState.Ideal);
  }
}

基础模型:

import 'package:flutter/material.dart';
import 'package:gray_green/enum/appState.dart';

class BaseModel extends ChangeNotifier {
  ViewState _viewState;

  ViewState get viewState => _viewState;

  setViewState(ViewState viewState) {
    _viewState = viewState;
    notifyListeners();
  }

  AuthState _authState;

  AuthState get authState => _authState;

  setAuthState(AuthState authState) {
    _authState = authState;
    notifyListeners();
  }

  // User _user;
  // set user(User user) {
  //   _user = user;
  //   notifyListeners();
  // }

  // get user => _user;

  // clear() {
  //   _user = null;
  //   notifyListeners();
  // }
}

AuthStateModelLogin:

import 'package:flutter/cupertino.dart';
import 'package:gray_green/enum/appState.dart';

import 'authModel.dart';
import 'baseModel.dart';

class authStateModelLogin extends BaseModel {
  switchAuthenticationState(AuthModel authModel) {
    authModel.authState == AuthState.SignIn
        ? authModel.setAuthState(AuthState.SignUp)
        : authModel.setAuthState(AuthState.SignIn);
  }

  switchAuthenticationMethod(
    AuthModel authModel,
    TextEditingController emailController,
    TextEditingController passwordController,
  ) {
    authModel.authState == AuthState.SignIn
        ? authModel.createNewUser(
            emailController.text,
            passwordController.text,
          )
        : authModel.signIn(
            emailController.text,
            passwordController.text,
          );
  }

  switchAuthenticationText(AuthModel authModel) {
    return authModel.authState == AuthState.SignIn ? "Sign Up" : "Sign in";
  }

  switchAuthenticationOption(AuthModel authModel) {
    return authModel.authState == AuthState.SignIn
        ? "Already registered?"
        : "Create account?";
  }
}

AuthPageLogin:

import 'package:flutter/material.dart';
import 'package:gray_green/enum/appState.dart';
import 'package:gray_green/model/authModel.dart';
import 'package:gray_green/model/authStateModelLogin.dart';

import 'ForgotPassword.dart';
import 'baseView.dart';

class AuthPageLogin extends StatelessWidget {
  final TextEditingController emailController;
  final TextEditingController passwordController;
  final AuthModel authModel;

  AuthPageLogin({
    @required this.emailController,
    @required this.passwordController,
    @required this.authModel,
  });
  @override
  Widget build(BuildContext context) {
    @override
        //User currentUser = FirebaseAuth.instance.currentUser;

        // FirebaseFirestore.instance
        //     .collection("users")
        //     .doc(currentUser.uid)
        //     .get()
        //     .then((DocumentSnapshot result) => Navigator.pushReplacement(
        //         context, MaterialPageRoute(builder: (context) => HomePage())))
        //     .catchError((err) => print(err));

        //  var snackBar = SnackBar(content: Text('User deso not exists'));
        final _formKey = GlobalKey<FormState>();

    return BaseView<authStateModelLogin>(
        builder: (context, authStateModelLogin, __) {
      return Scaffold(
        resizeToAvoidBottomInset: false,
        body: Padding(
          padding: const EdgeInsets.all(20),
          child: Center(
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  SizedBox(
                    height: 350,
                  ),
                  TextFormField(
                    validator: (value) {
                      if (value.isEmpty || !value.contains('@')) {
                        return 'Please enter a valid email address.';
                      }
                      return null;
                    },
                    keyboardType: TextInputType.emailAddress,
                    decoration: InputDecoration(hintText: "Email"),
                    key: ValueKey('email'),
                    controller: emailController,
                  ),
                  TextFormField(
                    key: ValueKey('passowrd'),
                    validator: (value) {
                      if (value.isEmpty || value.length < 7) {
                        return 'Password must be at least 7 characters long.';
                      }
                      return null;
                    },
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    controller: passwordController,
                  ),
                  authModel.viewState == ViewState.Busy
                      ? CircularProgressIndicator()
                      : SizedBox(
                          height: 25,
                        ),
                  ButtonTheme(
                    minWidth: 300.0,
                    height: 45.0,
                    child: RaisedButton(
                        child: Text(
                          authStateModelLogin
                              .switchAuthenticationText(authModel),
                          style: TextStyle(color: Colors.white),
                        ),
                        color: Theme.of(context).accentColor,
                        onPressed: () {
                          final isValid = _formKey.currentState.validate();
                          FocusScope.of(context).unfocus();

                          if (authModel.authState == AuthState.SignIn ||
                              isValid) {
                            _formKey.currentState.save();
                            authStateModelLogin.switchAuthenticationMethod(
                                authModel, emailController, passwordController);
                          } else {
                            var snackBar = SnackBar(
                                content:
                                    Text('email or passwors is incoreect'));
                            ScaffoldMessenger.of(context)
                                .showSnackBar(snackBar);

                            //    if (emailController != AuthState.SignIn) {
                            //  } else {
                          }
                          ;
                        }),
                  ),
                  SizedBox(
                    height: 5,
                  ),
                  if (authModel.authState != AuthState.SignIn)
                    FlatButton(
                      onPressed: () {
                        Navigator.pushNamed(
                          context,
                          ForgotPassword.id,
                        );
                      },
                      child: Text(
                        'Forgot Password?',
                        style: TextStyle(color: Colors.grey, fontSize: 12),
                      ),
                    ),
                  InkWell(
                    onTap: () {
                      authStateModelLogin.switchAuthenticationState(authModel);
                    },
                    child: Text(
                      authStateModelLogin.switchAuthenticationOption(authModel),
                      style: TextStyle(color: Colors.grey),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
    });
  }
}

我已将 authPageLogin 更改为此,因此我处理了异常但仍然是相同的错误

if (authModel.authState == AuthState.SignIn ||
                          isValid) {
                        _formKey.currentState.save();
                        try {
                             authStateModelLogin.switchAuthenticationMethod(
                              authModel,
                              emailController,
                              passwordController);
                        } catch (error) {
                          switch (error.code) {
                            case "ERROR_EMAIL_ALREADY_IN_USE":
                            case "account-exists-with-different-credential":
                            case "email-already-in-use":
                              return errorMessage =
                                  "Email already used. Go to login page.";
                              break;
                            case "ERROR_WRONG_PASSWORD":
                            case "wrong-password":
                              return errorMessage =
                                  "Wrong email/password combination.";
                              break;
                            case "ERROR_USER_NOT_FOUND":
                            case "user-not-found":
                            case "firebase_auth/user-not-found":
                              return errorMessage =
                                  "No user found with this email.";
                              break;
                            case "ERROR_USER_DISABLED":
                            case "user-disabled":
                              return errorMessage = "User disabled.";
                              break;
                            case "ERROR_TOO_MANY_REQUESTS":
                            case "operation-not-allowed":
                              return errorMessage =
                                  "Too many requests to log into this account.";
                              break;
                            case "ERROR_OPERATION_NOT_ALLOWED":
                            case "operation-not-allowed":
                              return errorMessage =
                                  "Server error, please try again later.";
                              break;
                            case "ERROR_INVALID_EMAIL":
                            case "invalid-email":
                              return errorMessage =
                                  "Email address is invalid.";
                              break;
                            default:
                              return errorMessage =
                                  "Login failed. Please try again.";
                              break;
                          }
                        }
                        var snackBar =
                            SnackBar(content: Text(errorMessage));

                        if (errorMessage != null) {
                          return ScaffoldMessenger.of(context)
                              .showSnackBar(snackBar);
                        }
                      }

【问题讨论】:

    标签: firebase flutter authentication firebase-authentication


    【解决方案1】:

    当用户不存在时,Firebase 会引发异常。所以你需要捕捉那个异常 在 AuthModel.signIn 中用 try catch 块包装 signInWithEmailAndPassword 并捕获异常。

    try{
    
        await firebaseAuth.signInWithEmailAndPassword(
            email: email, password: password);
    } catch (e){
    // show snackbar
    }
    

    最好创建一个错误处理程序类来处理异常

    编码的一些附注

    • 当您不想更改变量时,首选 final 而不是 var
    • 尝试编写依赖性较低的函数(例如,在 switchAuthenticationMethod 中,您要传递两个文本控制器。为什么不传递它们的文本?)
    • 对函数命名要敏感,以便其他人可以更快地阅读(再次例如 switchAuthenticationMethod 不是切换方法,它正在登录和注册)

    【讨论】:

    • 感谢您的笔记 :),但仍然是同样的例外
    • @Lama 再检查一遍
    • 现在它显示“断言失败:第 222 行 pos 12: 'context != null': is not true。”是不是因为我在 authModel 页面中定义了 BuildContext 上下文?
    【解决方案2】:

    您需要在switchAuthenticationMethod 方法之前添加await 关键字。

    您还需要在异步方法的返回类型中添加Future

    • createNewUser 方法更新为:
    Future<void> createNewUser(String email, String password) async {
     ...
    }
    
    • signIn 方法更新为:
    Future<void> signIn(String email, String password) async {
      ...
    }
    
    • logOut 方法更新为:
    Future<void> logOut() async {
      ...
    }
    
    • switchAuthenticationMethod 方法更新为:
    Future<void> switchAuthenticationMethod(
        AuthModel authModel,
        TextEditingController emailController,
        TextEditingController passwordController,
      ) {
      ...  
    }
    
    • 将您的登录功能更新为:
    if (authModel.authState == AuthState.SignIn || isValid) {
      _formKey.currentState.save();
      try {
        authStateModelLogin.switchAuthenticationMethod(
          authModel,
          emailController,
          passwordController);
      } catch (error) {
        switch (error.code) {
          ...                       
        }
      }
                            
    
      if (errorMessage != null) {
        var snackBar = SnackBar(content: Text(errorMessage));
        return ScaffoldMessenger.of(context).showSnackBar(snackBar);
      }
    }
    

    【讨论】:

    • 你需要在switchAuthenticationMethod方法之前添加await关键字是什么意思?但我尝试了但仍然相同的问题'未处理的异常:[firebase_auth/user-not-found]没有与此标识符对应的用户记录。该用户可能已被删除。'
    猜你喜欢
    • 2015-01-20
    • 2022-11-12
    • 2016-01-30
    • 1970-01-01
    • 2014-01-08
    • 2021-03-02
    • 2021-12-19
    • 2016-06-05
    • 2019-08-03
    相关资源
    最近更新 更多