Flutter类型错误:Object?无法赋值给List<Map<String,Object>>参数的解决方法
解决Flutter中Object?无法赋值给List<Map<String, Object>>的类型错误
问题根源
data['tutorial']和data['ingredients']的类型是Object?,而你的toList方法要求传入List<Map<String, Object>>类型参数。仅添加as List只能转换为List<dynamic>,无法满足泛型类型要求,因此报错。
解决方案1:精确类型转换+空安全处理
直接在调用toList时,将Object?转换为目标泛型类型,同时处理可能的空值:
修改recipe_helper.dart中的代码:
static List<Recipe> newlyPostedRecipe = newlyPostedRecipeRawData .map((data) => Recipe( title: data['title'] as String, photo: data['photo'] as String, description: data['description'] as String, // 先转换为List<dynamic>,再转为目标泛型,空值时返回空列表 tutorial: TutorialStep.toList((data['tutorial'] as List<dynamic>?)?.cast<Map<String, Object>>() ?? []), ingredients: Ingredient.toList((data['ingredients'] as List<dynamic>?)?.cast<Map<String, Object>>() ?? []), )) .toList();
解决方案2:优化toList方法参数类型
修改TutorialStep和Ingredient的toList方法,让它接受List<dynamic>类型参数,内部再做类型转换,这样调用更简洁:
修改TutorialStep类:
static List<TutorialStep> toList(List<dynamic> json) { return json .map((e) => TutorialStep.fromJson(e as Map<String, Object>)) .toList(); }
修改Ingredient类:
static List<Ingredient> toList(List<dynamic> json) { return json .map((e) => Ingredient.fromJson(e as Map<String, Object>)) .toList(); }
调用处简化:
static List<Recipe> newlyPostedRecipe = newlyPostedRecipeRawData .map((data) => Recipe( title: data['title'] as String, photo: data['photo'] as String, description: data['description'] as String, // 空值时返回空列表避免报错 tutorial: TutorialStep.toList((data['tutorial'] as List<dynamic>?) ?? []), ingredients: Ingredient.toList((data['ingredients'] as List<dynamic>?) ?? []), )) .toList();
额外提示
如果你的newlyPostedRecipeRawData是从JSON解析而来,建议提前给它指定类型,比如List<Map<String, dynamic>>,这样可以减少后续的类型转换操作,提升代码安全性。
内容的提问来源于stack exchange,提问作者Hayoloh
相关产品推荐
相关产品推荐

