skip to Main Content

I tried to display snackBar at the bottom when an error occurs by using the try … catch syntax as shown below, but for some reason, it is not displayed. Does anyone have a solution for this?

    Widget _confirmButton() {
    return SizedBox(
      height: 54,
      width: double.infinity,
      child: ElevatedButton(
        onPressed: () {
          try {
            _tryValidation();
            resetPassword(userEmail).then(
              (value) => Get.to(
                () => CompletePasswordReset(),
              ),
            );
          } catch (e) {
            const snackBar = SnackBar(
              content: Text('아이디 또는 비밀번호가 맞지 않습니다.'),
              backgroundColor: errorColor40,
              behavior: SnackBarBehavior.floating,
              margin: EdgeInsets.all(30),
              duration: Duration(seconds: 1),
            );
            ScaffoldMessenger.of(context).showSnackBar(snackBar);
          }
        },
        child: Text(
          '가입여부 확인',
          style: TextStyle(
            color: baseColor10,
            fontFamily: 'semi-bold',
            fontSize: titleMedium,
          ),
        ),
        style: ElevatedButton.styleFrom(
          backgroundColor: primaryColor50,
          elevation: 0,
          shadowColor: Colors.transparent,
          side: BorderSide(
            color: Colors.transparent,
          ),
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(15.0),
          ),
        ),
      ),
    );
  }

2

Answers


  1. You need to throw an error on your _tryValidation & resetPassword method/function

    Right now implementation has never reach the catch statement even the snackbar is working well.

    You can see here that by replacing the statement on the try block statement with

    throw 500;
    

    the snackbar is working well.

    try {
     throw 500;
    } catch (e) {
      const snackBar = SnackBar(
        content: Text('아이디 또는 비밀번호가 맞지 않습니다.'),
        backgroundColor: errorColor40,
        behavior: SnackBarBehavior.floating,
        margin: EdgeInsets.all(30),
        duration: Duration(seconds: 1),
      );
      ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }
    
    Login or Signup to reply.
  2. This snack bar need’s context you have to pass context in method instead of using this you can use Get-X Snack bar you can use it anywhere.
    Example;-

    Get.snackbar('아이디 또는 비밀번호가 맞지 않습니다', '',
        margin: EdgeInsets.all(15),
        padding: EdgeInsets.all(0),
        duration: Duration(milliseconds: 1000),
        snackPosition: SnackPosition.BOTTOM,
         );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search