Flutter路由跳转报错:String无法赋值给Route<Object?>参数
解决Flutter路由跳转类型不匹配错误
问题原因
你遇到的Error: The argument type 'String' can't be assigned to the parameter type 'Route<Object?>'错误,是因为直接将字符串格式的路由名称传给了Navigator的跳转方法(比如push/pushReplacement),但这类方法要求传入Route类型的对象,而非纯字符串。
具体解决方法
根据你的路由配置方式,选择对应方案:
方案1:使用命名路由跳转(推荐)
如果你的Routes类是用来定义路由名称常量的(比如static const String userInfo = '/userinfo'),验证成功后调用pushNamed或pushReplacementNamed方法跳转:
// 在VerificationPage的验证成功逻辑中 Navigator.pushNamed(context, Routes.userInfo); // 若需要替换当前页面(避免返回验证码页),用: Navigator.pushReplacementNamed(context, Routes.userInfo);
同时要确保在MaterialApp中已注册对应路由表:
MaterialApp( routes: { Routes.userInfo: (context) => UserInfoPage(), // 其他路由配置... }, );
方案2:直接构造Route对象跳转
如果不想用命名路由,直接通过MaterialPageRoute构造Route对象传入:
Navigator.push(context, MaterialPageRoute(builder: (context) => UserInfoPage())); // 替换当前页版本: Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => UserInfoPage()));
检查AuthRepository中的跳转逻辑
如果你的跳转逻辑是写在AuthRepository类中,要确保它接收BuildContext参数,并且同样使用上述正确的跳转方式,避免直接传字符串路由名。
内容的提问来源于stack exchange,提问作者Ahsan Raza
相关产品推荐
相关产品推荐

