azheen
azheen

Reputation: 977

flutter: Multiple widgets used the same GlobalKey error

i have a showSnackbar method that looks like this in my class provider class:

  GlobalKey<ScaffoldState> scaffoldKey =
      GlobalKey<ScaffoldState>(debugLabel: 'scaffoldKey');

  void showSnackBarE(String label) {
    if (purchasedItems[label] != 0) {
      final snackBar = SnackBar(
        content: Text("$label has already been added to cart!"),
        backgroundColor: Colors.black87,
        behavior: SnackBarBehavior.fixed,
        duration: Duration(seconds: 1),
      );
      scaffoldKey.currentState.removeCurrentSnackBar();
      scaffoldKey.currentState.showSnackBar(snackBar);
    } else {
      final snackBar = SnackBar(
        action: SnackBarAction(
            label: "Undo",
            onPressed: () {
              purchasedItems[label] = 0;
              getTotalSum();
            }),
        content: Text("$label has been added to cart!"),
        backgroundColor: Colors.black87,
        behavior: SnackBarBehavior.fixed,
        duration: Duration(seconds: 1),
      );
      scaffoldKey.currentState.removeCurrentSnackBar();
      scaffoldKey.currentState.showSnackBar(snackBar);
    }

    notifyListeners();
  }

at my TabsScreen im giving the scaffold the same key i used from provider

scaffold(
key: mainProvider.scaffoldkey,
..
...

every tab i have uses the same widget in which when the widget is pressed this snackbar will be called..

if i try to navigate back to the tabs screen like this:

                    Navigator.of(context)
                        .pushReplacementNamed(TabsScreen.id);

from a screen inside a screen from the tab bar appbar it gives me this error.. what should i do?

Upvotes: 0

Views: 1296

Answers (1)

David Czuchnowski
David Czuchnowski

Reputation: 101

As docs say to go back from the screen inside you should use Navigator.pop(context);

Edit: Ok so it seems that in this case the best solution is to use the Navigator.popUntil(context, ModalRoute.withName('screen_route')); function.

Upvotes: 1

Related Questions