参数类型“String”无法分配给参数类型“Route<Object?>”。.dart(argument_type_not_assignable)

3

我正在尝试在点击按钮时获取屏幕名称作为字符串(在自定义类中导航)。

class myButton extends StatelessWidget {
  String button_txt = '';
  String nextPage = '';
  double height_ = 39;

  myButton(button_txt) {
    this.button_txt = button_txt;
    this.nextPage = nextPage;
  }
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        Navigator.pushReplacement(context, '/$nextPage');
      },
2个回答

5
如果你想使用命名路由,应该像这样使用它:
Navigator.pushReplacementNamed(context, 'nextPage');

但是如果您不想使用命名路由,还有另一种导航方式:

  Navigator.pushReplacement(
    context,
    MaterialPageRoute(
      builder: (context) {
        return routewidget;
      },
    ),
  );

nextPage 可以获取不同的值,它并非硬编码,这就是我的问题。 - Mohale Nakana

1
有两种方法可以实现这个目标:
  • 使用Navigator.pushNamedReplacement(context, '/$nextPage')
  • 使用带有路由参数的Navigator.pushReplacement(context, route);
如果您想要使用命名路由,则使用
Navigator.pushNamedReplacement(context, '/name/of/route)
如果仍然无法正常工作,则可能没有正确设置导航
如果您想要使用非命名路由,则方法会有所不同:
Navigator.pushReplacement(
  context,
  MaterialPageRoute( // Material page route makes it
    // slide from the bottom to the top
    // 
    // If you want it to slide from the right to the left, use 
    // `CupertinoPageRoute()` from the cupertino library.
    // 
    // If you want something else, then create your own route
    // https://flutter.dev/docs/cookbook/animation/page-route-animation
    builder: (context) {
      return NextPageWidget();
    },
  ),
);

我正在尝试使用Navigator.pushNamedReplacement(context, '/$nextPage'),但它无法正常工作,并且抱怨了我在这个问题上提出的错误。 - Mohale Nakana
谢谢,它起作用了。我将Navigator.pushReplacement替换为Navigator.pushNamedReplacement。 - Mohale Nakana

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接