Why sometimes snackbar is failing

170

Try to check if the widget is still mounted in the three:

void showFailedSnackBar(String s) {
    if (mounted) {
    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

    ScaffoldMessenger.of(context).showSnackBar(snackBar);
    }

  }
Share:
170
inter cretasyo
Author by

inter cretasyo

Updated on December 28, 2022

Comments

  • inter cretasyo
    inter cretasyo over 1 year

    Please help to explain why sometimes my SnackBar is showing an error. I don't understand at which circumstance the issue will come. I just want to point also that even though it is showing the error, in the app itself, it is working fine.

    Here's my code:

    void showFailedSnackBar(String s) {
        SnackBar snackBar = SnackBar(
          content: Text(s),
          duration: Duration(seconds: 3),
          backgroundColor: Theme.of(context).primaryColor,
        );
    
        ScaffoldMessenger.of(context).showSnackBar(snackBar);
      }
    

    Here's the error:

    E/flutter ( 7879): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
    E/flutter ( 7879): Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.