颤振:多个小部件使用相同的 GlobalKey 错误 [英] flutter: Multiple widgets used the same GlobalKey error

查看:49
本文介绍了颤振:多个小部件使用相同的 GlobalKey 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的类提供程序类中有一个 showSnackbar 方法,如下所示:

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

在我的 TabsScreen 中,我为脚手架提供了我从提供者那里使用的相同密钥

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?

推荐答案

正如文档所说从屏幕里面返回你应该使用Navigator.pop(context);

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

好的,在这种情况下,似乎最好的解决方案是使用 Navigator.popUntil(context, ModalRoute.withName('screen_route')); 函数.

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

这篇关于颤振:多个小部件使用相同的 GlobalKey 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆