Why sometimes snackbar is failing

Viewed 397

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.
3 Answers

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);
    }

  }

In your function showSnackbar, besides the String you could also pass a BuildContext context variable, so you know which context you pass e.g.

    SnackBar snackBar = SnackBar(
      content: Text(s),
      duration: Duration(seconds: 3),
      backgroundColor: Theme.of(context).primaryColor,
    );

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

You could save the context of the scaffold that you are sure it exists in a provider in order to pass it around where you need it.

https://velog.io/@namtaehyun/Flutter-This-widget-has-been-unmounted-so-the-State-no-longer-has-a-context

define global navigator context in main.dart, and use it everywhere

// main.dart

final navigatorKey = GlobalKey<NavigatorState>(); // define global key

void main() => runApp(
  MaterialApp(
    ...
    navigatorKey: navigatorKey, // propagate to all descendant contexts
  ),
);


// other.dart

void showMyDialog() {
  showDialog(
    context: navigatorKey.currentContext, // reference global context
    builder: (context) => ...
  );
}
Related