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

Flutter调用Provider.of<dynamic>报错,编辑产品页面无法跳转

问题解决:Flutter编辑产品页面Provider.of报错处理

错误原因

报错的核心是调用Provider.of时未明确指定泛型类型,Dart自动推断类型为dynamic,而Provider库禁止这种用法(会导致类型不安全)。具体触发位置在didChangeDependencies方法的这行代码:

_editedProduct = Provider.of(context, listen: false).findById(productId);

解决方法

给Provider.of添加明确的泛型类型<Products>,因为你要获取的是Products类型的Provider实例:

修改后的didChangeDependencies方法代码:

@override
void didChangeDependencies() {
  if (_isInit) {
    final productId = ModalRoute.of(context)!.settings.arguments as String?;
    if (productId != null) {
      // 添加<Products>泛型指定类型
      _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();
}

额外注意

确保你的Products类已经在Widget树的上层(比如App根节点)通过ChangeNotifierProvider或其他Provider方式提供了实例,否则会出现“找不到Provider”的后续错误。

内容的提问来源于stack exchange,提问作者Tooraj rezaei

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 23:04:55