You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter开发报错:MaterialPageRoute无法赋值给String参数,求解决

错误原因

Navigator.pushNamed的第二个参数要求传入路由名称字符串,但你传入了MaterialPageRoute对象,类型不匹配,直接触发了类型错误。

解决方案

方案一:改用Navigator.push

Navigator.push方法支持直接传入MaterialPageRoute对象,修改代码如下:

onTap: () {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (context) => ProductDetails(
        id: bottleCategory.bottleList[index].id,
        bottleName: bottleCategory.bottleList[index].bottleName,
        image: bottleCategory.bottleList[index].image,
        price: bottleCategory.bottleList[index].price,
      ),
    ),
  );
}

方案二:使用命名路由传参

如果坚持用Navigator.pushNamed,需要先注册命名路由,再通过参数传递数据:

  1. 在MaterialApp中注册路由:
MaterialApp(
  routes: {
    '/productDetails': (context) => ProductDetails(),
  },
)
  1. 调整跳转代码,通过arguments传递数据:
onTap: () {
  Navigator.pushNamed(
    context,
    '/productDetails',
    arguments: {
      'id': bottleCategory.bottleList[index].id,
      'bottleName': bottleCategory.bottleList[index].bottleName,
      'image': bottleCategory.bottleList[index].image,
      'price': bottleCategory.bottleList[index].price,
    },
  );
}
  1. 在ProductDetails页面中获取参数:
class ProductDetails extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final args = ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>;
    return Scaffold(
      // 使用args['id']、args['bottleName']等获取传递的数据
    );
  }
}

内容的提问来源于stack exchange,提问作者Anesu Mazvimavi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 13:35:45