【问题标题】:The argument type 'String' can't be assigned to the parameter type 'Route<Object?>'.dart(argument_type_not_assignable)参数类型 'String' 不能分配给参数类型 'Route<Object?>'.dart(argument_type_not_assignable)
【发布时间】:2021-09-16 14:59:21
【问题描述】:

单击按钮时,我试图将要导航到的屏幕名称作为字符串(在自定义类中)。

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    有两种方法可以做到这一点:

    • 使用Navigator.pushNamedReplacement(context, '/$nextPage')
    • Navigator.pushReplacement(context, route); 与路由参数一起使用

    如果您想使用命名路由,请使用
    Navigator.pushNamedReplacement(context, '/name/of/route)
    如果它仍然不起作用,那么您可能没有set up navigation properly

    如果你想使用未命名的路由,那么方法会有所不同:

    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') 但它不起作用并抱怨我在这个问题上提出的错误。
    • 谢谢,用 Navigator.pushNamedReplacement 替换了 Navigator.pushReplacement。
    【解决方案2】:

    如果你想使用命名路由,你应该像这样使用它:

    Navigator.pushReplacementNamed(context, 'nextPage');
    

    但如果您不想使用命名路线,则可以使用不同的导航方式:

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

    【讨论】:

    • nextPage 可以得到不同的值,不是硬编码的,那是我的问题
    【解决方案3】:

    Navigator.pushReplacement 更改为Navigator.pushNamedReplacement

    【讨论】:

    • 我认为其他答案已经涵盖了这一点。
    猜你喜欢
    • 1970-01-01
    • 2021-09-25
    • 2021-09-15
    • 1970-01-01
    • 2021-10-20
    • 2019-04-23
    • 2020-04-15
    • 2023-02-18
    • 2021-09-30
    相关资源
    最近更新 更多