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,需要先注册命名路由,再通过参数传递数据:
- 在
MaterialApp中注册路由:
MaterialApp( routes: { '/productDetails': (context) => ProductDetails(), }, )
- 调整跳转代码,通过
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, }, ); }
- 在
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
相关产品推荐
相关产品推荐

