扑火的firebaseauth异常问题

时间:2020-11-09 18:36:23

标签: flutter

我还不太熟悉,所以我尝试在登录时捕获身份验证错误,并希望在登录屏幕中显示该错误。我正在从另一个文件执行所有身份验证服务,我想从那里获取异常并进入我的登录屏幕

这来自我的authservice类

Future loginWithEmailpasswd(String email, String password) async {
    try {
      return await _auth.signInWithEmailAndPassword(
          email: email, password: password);
    } on FirebaseAuthException catch (e) {
      print(e.toString());
      message=e.toString();

    }

当我按下登录按钮并将值传递给authservice类时,如果有任何异常,我希望将消息从authservice传递到登录屏幕


class StudentLoginScreen extends StatefulWidget {
  final Function toggleView;
  StudentLoginScreen({this.toggleView});

  @override
  _StudentLoginScreenState createState() => _StudentLoginScreenState();
}

final _formkey = GlobalKey<FormState>();

class _StudentLoginScreenState extends State<StudentLoginScreen> {
  String email = '';
  String password = '';
  String message = '';
  final AuthService _authService = AuthService();
  //SharedPreferences usertype;
  @override
  Widget build(BuildContext context) {
    Size size = MediaQuery.of(context).size;

    return Scaffold(
      backgroundColor: HexColor(studentPrimaryColour),
      body: SafeArea(
        child: SingleChildScrollView(
          child: Form(
            key: _formkey,
            child: Column(
              children: <Widget>[
                showAlert(),
                SizedBox(
                  height: 25.0,
                ),
                HeadingText(
                  text: 'Login',
                  size: 60.0,
                  color: Colors.white,
                ),
                SizedBox(
                  height: 25.0,
                ),
                RoundedInputField(
                  hintText: "Email",
                  validator: (val) =>
                      val.isEmpty ? 'Oops! you left this field empty' : null,
                  onChanged: (val) {
                    email = val;
                  },
                ),
                SizedBox(
                  height: 5.0,
                ),
                RoundedInputField(
                  hintText: "Password",
                  validator: (val) =>
                      val.isEmpty ? 'Oops! you left this field empty' : null,
                  boolean: true,
                  onChanged: (val) {
                    password = val;
                  },
                ),
                SizedBox(
                  height: 15.0,
                ),
                Container(
                  margin: EdgeInsets.symmetric(vertical: 10),
                  width: size.width * 0.8,
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(29),
                    child: FlatButton(
                      padding:
                          EdgeInsets.symmetric(vertical: 20, horizontal: 40),
                      color: Colors.white,
                      onPressed: () async {
                        if (_formkey.currentState.validate()) {
                          dynamic result = await _authService
                              .loginWithEmailpasswd(email, password);
                          print(email);
                          print(password);
                          if (result != null) {
                            print('logged in');
                          } else {
                            print('error logging in');
                            setState(() {
                              message = // initialize value from authservice
                            });
                          }
                        }
                      },
                      child: Text(
                        'login',
                        style: GoogleFonts.montserrat(
                            color: HexColor(studentPrimaryColour),
                            fontSize: 20),
                      ),
                    ),
                  ),
                ),
                SizedBox(
                  height: 15.0,
                ),
                InkWell(
                  onTap: () {
                    widget.toggleView();
                  },
                  child: HeadingText(
                    text: 'register?',
                    color: Colors.white,
                    size: 10,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget showAlert() {
    if (_message != null) {
      return Container(
        color: Colors.amber,
        padding: EdgeInsets.all(8.0),
        child: Row(
          children: <Widget>[
            Icon(Icons.error_outline_rounded),
            Expanded(
                child: AutoSizeText(
              _message,
              maxLines: 3,
            ))
          ],
        ),
      );
    }
    return SizedBox(
      height: 0,
    );
  }
}


有什么方法可以在我的登录屏幕上不实施authservice?

1 个答案:

答案 0 :(得分:0)

正确且最优雅的方法如注释中所述。将您的应用程序分解为服务和模型。您可以将这些模型与任何State Management方法一起使用。

您可以设置一个模型类,该模型类可能具有身份验证的结果或其提供的错误。这应该是连接包装返回的内容。

但是,一个有教育性且简单的建议(无论如何都不优雅)将是rethrow异常并在外部再次捕获它:

Future loginWithEmailpasswd(String email, String password) async {
    try {
      return await _auth.signInWithEmailAndPassword(
          email: email, password: password);
    } on FirebaseAuthException catch (e) {
      print(e.toString());
      rethrow;
    }

然后,在按钮回调上:

[...]
Try{
    dynamic result = await _authService
                              .loginWithEmailpasswd(email, password);    
    print('logged in');
}on FirebaseAuthException catch (e) {
      setState(() {
          message = e.toString();
      });
    }
}
[...]

正如我所说,这根本不是优雅的或可读的。我将此答案发布为使用throw的替代方法。