我试图导航从一个屏幕到另一个与路线。当我点击按钮页面移动到路由提供我得到错误

I/flutter ( 8790): Another exception was thrown: There are multiple heroes that share the same tag within a subtree.

代码如下:

路线:

 <String, WidgetBuilder>{
    '/first':(BuildContext context) =>NavigatorOne() ,
    '/second':(BuildContext context) =>NavigatorTwo(),
    '/third':(BuildContext context) =>NavigatorThree(),

  },

Navigator.of(context).pushNamed('/first');
Navigator.of(context).pushNamed('/second');
Navigator.of(context).pushNamed('/third');

class NavigatorOne extends StatefulWidget {
  @override
  _NavigatorOneState createState() =>  _NavigatorOneState();
}

class _NavigatorOneState extends State<NavigatorOne> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(

      appBar: AppBar(),
      body: Container(
      color: Colors.green,
      child: RaisedButton(child: Text(' one 1'),onPressed: (){
        Navigator.of(context).pushNamed('/second');
      },),
    ),
    ); 
  }
}

错误:

══╡ EXCEPTION CAUGHT BY SCHEDULER LIBRARY ╞═════════════════════════════════════════════════════════ I/flutter (21786): The following assertion was thrown during a scheduler callback: I/flutter (21786): There are multiple heroes that share the same tag within a subtree. I/flutter (21786): Within each subtree for which heroes are to be animated (typically a PageRoute subtree), each Hero I/flutter (21786): must have a unique non-null tag. I/flutter (21786): In this case, multiple heroes had the following tag: <default FloatingActionButton tag>

我怎么解决这个问题?


当前回答

对我来说,只是添加一个独特的heroTag到我的FloatingActionButtons没有工作。我最终在一个文本小部件中包装了heroTag,这为我解决了问题。

new FloatingActionButton(
    heroTag: Text("btn1"),
    ...
)

new FloatingActionButton(
    heroTag: Text("btn2"),
    ...
)

其他回答

你可以设置一个唯一的id或只设置null:

FloatingActionButton(
  heroTag: null,
  ...
)

如果有多个具有相同标记的项目,则只需设置tag: Uuid()。

添加任意数量的小部件,使用英雄标签作为字符串

  Widget floatingButt(Function function, IconData icon, String heroTag) {
    return FloatingActionButton(
      onPressed: function,
      heroTag: heroTag,
      materialTapTargetSize: MaterialTapTargetSize.padded,
      backgroundColor: Constants.primaryColor, // from your values file
      child: Icon(
        icon,
        size: 36.0,
      ),
    );
  }

我遇到了同样的错误。这是因为在一个屏幕上多次使用浮动动作按钮等按钮。 以前我使用浮动动作按钮,而不是我把它改成一个手势探测器来使用ontap,所以它工作

  GestureDetector(

              //backgroundColor: Colors.amber[100],
              onTap: add,
              child: Icon(
                FontAwesomeIcons.plus,
                size: 30,
              ),
            ),
            SizedBox(
              width: 20,
            ),
            GestureDetector(
             // heroTag: "btn2",
             // backgroundColor: Colors.amber[100],
              onTap: sub,
              child: Icon(FontAwesomeIcons.minus, size: 30),
            ),

还有另一种方法:

FloatingActionButton(
    heroTag: UniqueKey(),
    ....  
)

https://api.flutter.dev/flutter/foundation/UniqueKey-class.html

UniqueKey () 创建一个只等于它本身的键。