SnackBar未显示。

huangapple go评论57阅读模式
英文:

SnackBar is not displying

问题

以下是您要翻译的内容:

这是一个独立的Dart文件,包含Snackbar小部件:

import 'package:flutter/material.dart';
import 'package:app/globals.dart' as globals;

class ErrorAlert {
  showAlert(context, message) {
    return ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        backgroundColor: globals.mainColor,
        content: Text(message),
        duration: const Duration(seconds: 5),
        action: SnackBarAction(
          label: 'Dismiss',
          textColor: Colors.white,
          onPressed: () {
            ScaffoldMessenger.of(context).hideCurrentSnackBar();
          },
        ),
      )
    );
  }
}

这是我调用它的代码(在捕获部分的条件中):

signInWithEmailIdAndPassword(email, password, context) async {
    try {
      UserCredential result = await fireAuth.signInWithEmailAndPassword(email: email, password: password);
      User user = result.user!;
      // checkUser = user; //返回用户ID
      if(result != null) {
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const HomeScreen()));
      }
    }
    catch(signError) {
      if(signError is PlatformException) {
        if(signError.code == 'ERROR_WRONG_PASSWORD') {
          ErrorAlert().showAlert(context, 'Wrong Password!');
        } else if(signError.code == 'ERROR_INVALID_EMAIL') {
          ErrorAlert().showAlert(context, 'Invalid Email ID!');
        } else if(signError.code == 'ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL') {
          ErrorAlert().showAlert(context, 'Account is already exists with different credentials!');
        } else if(signError.code == 'ERROR_USER_NOT_FOUND') {
          ErrorAlert().showAlert(context, 'User not found!');
        }
        print(signError);
      }
    }
    // return checkUser;
}

这是在控制台中显示的调试消息:

E/RecaptchaCallWrapper(32567): Initial task failed for action RecaptchaAction(action=signInWithPassword) with exception - The email address is badly formatted.
英文:

So, I have created one snackbar widget in different dart file and I'm calling it in different dart file with context and text message. but when I'm getting error at that time snackbar is not showing on screen.

This is Separate dart file that contains Snackbar widget:

import 'package:flutter/material.dart';
import 'package:app/globals.dart' as globals;

class ErrorAlert{

  showAlert(context, message) {
    return ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        backgroundColor: globals.mainColor,
        content: Text(message),
        duration: const Duration(seconds: 5),
        action: SnackBarAction(
          label: 'Dismiss',
          textColor: Colors.white,
          onPressed: () {
            ScaffoldMessenger.of(context).hideCurrentSnackBar();
          },
        ),
      )

    );
  }

}

Here the Code from where I'm calling it (in catch part if condition):

signInWithEmailIdAndPassword(email,password, context) async {
    try {
      UserCredential result = await fireAuth.signInWithEmailAndPassword(email: email, password: password);
      User user = result.user!;
      // checkUser = user; //returns UserID
      if(result != null) {
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const HomeScreen()));
      }
    }
    catch(signError) {
      if(signError is PlatformException) {
        if(signError.code == 'ERROR_WRONG_PASSWORD') {
          ErrorAlert().showAlert(context, 'Wrong Password!');
        } else if(signError.code == 'ERROR_INVALID_EMAIL') {
          ErrorAlert().showAlert(context, 'Invalid Email ID!');
        } else if(signError.code == 'ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL') {
          ErrorAlert().showAlert(context, 'Account is already exists with different credentials!');
        } else if(signError.code == 'ERROR_USER_NOT_FOUND') {
          ErrorAlert().showAlert(context, 'User not found!');
        }
        print(signError);
      }
    }
    // return checkUser;
  }

This is the debug message that is showing in console:

E/RecaptchaCallWrapper(32567): Initial task failed for action RecaptchaAction(action=signInWithPassword)with exception - The email address is badly formatted.

答案1

得分: 1

你试图捕获的异常没有在正确的 if 嵌套中。
目前,你首先尝试检查它是否是 PlatformException,而 Firebase 抛出的是 FirebaseAuthException

你应该尝试以下操作:

signInWithEmailIdAndPassword(email, password, context) async {
    try {
      UserCredential result = await fireAuth.signInWithEmailAndPassword(email: email, password: password);
      User user = result.user!;
      // checkUser = user; //返回用户ID
      if (result != null) {
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const HomeScreen()));
      }
    }
    catch (signError) {
      if (signError is PlatformException) {
        // 做一些操作
       
      }
      if (signError is FirebaseAuthException) {
         if (signError.code == 'ERROR_WRONG_PASSWORD') {
          ErrorAlert().showAlert(context, '密码错误!');
        } else if (signError.code == 'ERROR_INVALID_EMAIL') {
          ErrorAlert().showAlert(context, '无效的电子邮件地址!');
        } else if (signError.code == 'ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL') {
          ErrorAlert().showAlert(context, '帐户已经存在,使用不同的凭据!');
        } else if (signError.code == 'ERROR_USER_NOT_FOUND') {
          ErrorAlert().showAlert(context, '用户未找到!');
        } else {
          ErrorAlert().showAlert(context, '出了点问题!');
        }
      }
    }
    // 返回 checkUser;
  }

此外,始终检查所有情况,确保没有 else 状态。

另外,请确保为 Firebase 使用正确的返回代码,如果我记得正确,无效的电子邮件代码是 invalid-email,但你可能已经有一个覆盖它的常量。

英文:

The exception you are trying to catch is not in the right if nesting.
At the moment you are first trying to check if it is a PlatformException whereas Firebase is throwing FirebaseAuthException

You should try the following:

signInWithEmailIdAndPassword(email,password, context) async {
    try {
      UserCredential result = await fireAuth.signInWithEmailAndPassword(email: email, password: password);
      User user = result.user!;
      // checkUser = user; //returns UserID
      if(result != null) {
        Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => const HomeScreen()));
      }
    }
    catch(signError) {
      if(signError is PlatformException) {
        // DO STUFF
       
      }
      if (signError is FirebaseAuthException) {
         if(signError.code == 'ERROR_WRONG_PASSWORD') {
          ErrorAlert().showAlert(context, 'Wrong Password!');
        } else if(signError.code == 'ERROR_INVALID_EMAIL') {
          ErrorAlert().showAlert(context, 'Invalid Email ID!');
        } else if(signError.code == 'ERROR_ACCOUNT_EXISTS_WITH_DIFFERENT_CREDENTIAL') {
          ErrorAlert().showAlert(context, 'Account is already exists with different credentials!');
        } else if(signError.code == 'ERROR_USER_NOT_FOUND') {
          ErrorAlert().showAlert(context, 'User not found!');
        } else {
          ErrorAlert().showAlert(context, 'Something went wrong!');
        }
      }
    }
    // return checkUser;
  }

Also always check all the cases here you had no else status.

Additionally make sure to have the correct return codes for Firebase as if I remember correctly the invalid email code is invalid-email but you may already have constant that covers it.

答案2

得分: 0

以下是翻译好的部分:

"So for this is the problem with the context actually for better understanding you can refer this thread"
"这是关于上下文的问题,为了更好地理解,您可以参考此帖子"
https://stackoverflow.com/questions/52088889/can-someone-explain-to-me-what-the-builder-class-does-in-flutter

"And to resolve your issue you can do it like this."
"要解决您的问题,可以这样做。"

"new Builder(builder: (BuildContext context) {
return GestureDetector(
onTap: () {
ErrorAlert().showAlert(context, 'Wrong Password!');
},
child: const Text('click'));
})"
"新建 Builder(builder: (BuildContext 上下文) {
return GestureDetector(
onTap: () {
ErrorAlert().showAlert(context, '密码错误!');
},
child: const Text('点击'));
})"

英文:

So for this is the problem with the context actually for better understanding you can refer this thread
https://stackoverflow.com/questions/52088889/can-someone-explain-to-me-what-the-builder-class-does-in-flutter

And to resolve your issue you can do it like this.

new Builder(builder: (BuildContext context) {
          return GestureDetector(
              onTap: () {
                ErrorAlert().showAlert(context, 'Wrong Password!');
              },
              child: const Text('click'));
        })

huangapple
  • 本文由 发表于 2023年6月12日 21:10:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76457008.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定