Flutter:是否有更好的方法来处理if / else语句中每个条件的setState调用?

问题描述

我有未优化的代码。基本上,如果发生FirebaseAuthException,我想更改errorString的值。我该使用ChangeNotifier吗?

Future<void> _signInWithEmailAndPassword(BuildContext context,AsyncSnapshot<String> userSnapshot,AsyncSnapshot<String> passwordSnapshot) async {
    try {
      final auth = Provider.of<AuthService>(context,listen: false);
      await auth.signInWithEmailAndPassword(
          userSnapshot.data.trim(),passwordSnapshot.data.trim());
          setState(() => errorString = 'Success');
    } on FirebaseAuthException catch (e) {
      // I don't want to call setState() in each condition
      if (e.code == 'invalid-credential') {
        setState(() {
          errorString = "Email address appears to be malformed/expired";
        });
      } else if (e.code == 'wrong-password') {
        setState(() {
          errorString = "Password associated with this email is wrong";
        });
      } else if (e.code == 'user-not-found') {
        setState(() {
          errorString = "Email has not been registered,please sign up :)";
        });
      } else if (e.code == 'user-disabled') {
        setState(() {
          errorString = "User with this email has been disabled :(";
        });
      } else if (e.code == 'too-many-requests') {
        setState(() {
          errorString = "Too many requests,please try again later.";
        });
      } else if (e.code == 'operation-not-allowed') {
        setState(() {
          errorString = "Signing in with email and password is not enabled";
        });
      } else if (e.code == 'account-exists-with-different-credential') {
        setState(() {
          errorString =
              "Email has already been registered. Reset your password.";
        });
      }
    } 
  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)