Flutter路由参数报错Expected String got Null 新增编辑商品页问题求助
问题排查与修复方案
1. 核心报错原因:路由参数强制类型转换错误
你当前代码中直接将路由参数强制转为非空String类型:
final productId = ModalRoute.of(context)!.settings.arguments as String;
新增商品场景下跳转路由没有传递arguments,此时参数值为Null,强制转为String就会触发你遇到的Expected a value of type 'String', but got one of type 'Null'报错。
修复方式:改用可空类型接收参数,移除不必要的非空断言:
final productId = ModalRoute.of(context)?.settings.arguments as String?;
修改后即使没有传参,productId会为null,你后续的非空判断逻辑才能正常生效。
2. 其他隐藏问题修复
- 表单初始值key不匹配:你在给
_initValues赋值价格的时候用了大写key'Price',但初始定义和取值时用的是小写'price',会导致编辑场景下价格输入框拿不到初始值,将赋值的key改为小写即可。 - 保存逻辑判断写反:
_saveForm方法中if (isValid) { return; }逻辑错误,表单验证通过反而直接返回不执行保存,修改为if (!isValid) { return; }即可。 - 新增/编辑判断逻辑错误:
_editedproduct初始化时id为空字符串而非null,所以if (_editedproduct.id != null)永远为真,新增场景也会走更新逻辑,修改为if (_editedproduct.id.isNotEmpty)即可。
修复后的didChangeDependencies参考代码
@override void didChangeDependencies() { if (_isinit) { final productId = ModalRoute.of(context)?.settings.arguments as String?; if (productId != null) { _editedproduct = Provider.of<Products>(context, listen: false).FindByID(productId); _imageUrlController.text = _editedproduct.imageUrl; _initValues = { 'title': _editedproduct.title, 'description': _editedproduct.description, 'price': _editedproduct.price.toString(), 'imageUrl': '', }; } } _isinit = false; super.didChangeDependencies(); }
内容的提问来源于stack exchange,提问作者Rex
相关产品推荐
相关产品推荐

