Flutter购物应用报type 'Null' is not a subtype of type 'String'错误如何解决
错误原因
- 核心错误触发点为
didChangeDependencies方法中final productId = ModalRoute.of(context)!.settings.arguments as String;这行代码:- 页面跳转未传递路由参数、或传递参数为null时,直接用
as String强转null值,触发类型不匹配异常 - Provider调用语法错误:
Provider.of(context)<Products>(context, listen: false)多传入了多余的context参数,泛型位置错误,同时未调用查询单个商品的方法,直接将整个Products集合实例赋值给单个Product类型变量,也会触发类型异常
- 页面跳转未传递路由参数、或传递参数为null时,直接用
修复方案
1. 修正didChangeDependencies逻辑,增加空校验与类型校验
@override void didChangeDependencies() { if (_isInit) { // 先获取路由参数,不直接强转 final args = ModalRoute.of(context)?.settings.arguments; // 仅当参数为非空字符串时执行编辑逻辑 if (args != null && args is String && args.isNotEmpty) { final productId = args; // 修正Provider调用写法,补充按ID查询单个商品逻辑 _editedProduct = Provider.of<Products>(context, listen: false).findById(productId); _initvalues = { 'title': _editedProduct.title, 'description': _editedProduct.description, 'price': _editedProduct.price.toString(), 'imageUrl': '' }; _imageUrlController.text = _editedProduct.imageUrl; } _isInit = false; super.didChangeDependencies(); } }
2. 补充Products类的按ID查询方法
如果你的Products类尚未实现按id查询商品的逻辑,补充对应方法:
class Products with ChangeNotifier { // 你的商品列表 final List<Product> _items = []; // 补充按ID查询商品方法 Product findById(String id) { return _items.firstWhere((product) => product.id == id); } // 其余原有代码不变 }
3. 校验路由跳转逻辑
确认跳转进入EditProductScreen页面的代码符合如下规范:
// 新增商品场景,不需要传参数 Navigator.pushNamed(context, EditProductScreen.routeName); // 编辑商品场景,传入对应商品的id字符串 Navigator.pushNamed(context, EditProductScreen.routeName, arguments: existingProduct.id);
内容的提问来源于stack exchange,提问作者Niranjan kumar
相关产品推荐
相关产品推荐

