Search code examples
fluttertextfieldflutter-getxsnackbar

SnackBars in flutter only shows once


I want to give an error warning if the input given in the text field is not correct (like the field only accepts integer and not characters or strings). I have used Get.snackbar for giving the error warning . but it show only once after opening the application. How to solve this issue {Thanks in advance}


Solution

  • first create a title for you snackbar as a string

    String? sbTitle;
    

    then you can create a function which can show snackBar every time you call it

    void showSnackBar(BuildContext context) {
      final scaffold = ScaffoldMessenger.of(context);
      scaffold.showSnackBar(
        SnackBar(
          content: Text(sbTitle!),
          action: SnackBarAction(
              label: 'Ok', onPressed: scaffold.hideCurrentSnackBar),
        ),
      );
    }
    

    and finally every time you want to show and error just set the title to your error code and pass in the function like this

     sbTitle = "Invalid input";
     showSnackBar(context);
    

    this will save you so much time cause you dont have to build snackbar every time you want to show snackbar