Flutter请求API时出现NoSuchMethodError空对象调用[]方法问题
Flutter API请求NoSuchMethodError异常排查与解决
原始错误信息
执行热重启... 正在同步文件到设备sdk gphone x86 64 arm64... 应用已在777ms内重启。 E/flutter (21101): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: NoSuchMethodError: 在null上调用了方法'[]'。 E/flutter (21101): 接收者: null E/flutter (21101): 尝试调用: [] E/flutter (21101): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5) E/flutter (21101): #1 new Recipe.fromJson (package:food_recipe_app_1/models/recipe.dart:16:19) E/flutter (21101): #2 Recipe.recipesFromSnapshot.<匿名方法> (package:food_recipe_app_1/models/recipe.dart:25:21) E/flutter (21101): #3 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31) E/flutter (21101): #4 ListIterator.moveNext (dart:_internal/iterable.dart:342:26) E/flutter (21101): #5 new _GrowableList._ofEfficientLengthIterable (dart:core-patch/growable_array.dart:189:27) E/flutter (21101): #6 new _GrowableList.of (dart:core-patch/growable_array.dart:150:28) E/flutter (21101): #7 new List.of (dart:core-patch/array_patch.dart:51:28) E/flutter (21101): #8 ListIterable.toList (dart:_internal/iterable.dart:213:44) E/flutter (21101): #9 Recipe.recipesFromSnapshot (package:food_recipe_app_1/models/recipe.dart:26:8) E/flutter (21101): #10 RecipeApi.getRecipe (package:food_recipe_app_1/models/recipe.api.dart:26:19) E/flutter (21101): E/flutter (21101): #11 _HomePageState.getRecipes (package:food_recipe_app_1/views/home.dart:25:16)
原始Recipe实体类代码
class Recipe { final String name; final String images; final double rating; final String totalTime; Recipe({ this.name, this.images, this.rating, this.totalTime, }); factory Recipe.fromJson(dynamic json) { return Recipe( name: json['name'] as String, images: json['images'][0]['hostedLargeUrl'] as String, rating: json['rating'] as double, totalTime: json['totalTime'] as String ); } static List<Recipe> recipesFromSnapshot(List snapshot) { return snapshot.map((data) { return Recipe.fromJson(data); }).toList(); } @override String toString() { return 'Recipe {name: $name, image: $images, rating: $rating, totalTime: $totalTime}'; } }
错误原因分析
从异常栈追踪可定位到错误发生在Recipe.fromJson方法第16行:json['images'][0]['hostedLargeUrl'],触发NoSuchMethodError的核心原因是在null对象上调用了[]运算符,具体场景包括:
- API返回的部分Recipe数据中,
images字段不存在或值为null - API返回的
images是一个空数组,调用[0]取第一个元素得到null,后续访问hostedLargeUrl时触发错误 - 传入
fromJson的json对象本身为null(比如API返回的列表中存在null元素)
解决方法
针对上述问题,需要在序列化过程中增加多层空安全校验,同时将实体类字段改为可空类型避免类型转换错误:
修改后的Recipe实体类代码
class Recipe { final String? name; final String? images; final double? rating; final String? totalTime; Recipe({ this.name, this.images, this.rating, this.totalTime, }); factory Recipe.fromJson(dynamic json) { // 校验整个json对象是否为null if (json == null) { return Recipe(); } // 逐层校验images嵌套字段 String? imageUrl; final imagesList = json['images']; if (imagesList is List && imagesList.isNotEmpty) { final firstImage = imagesList[0]; if (firstImage != null) { imageUrl = firstImage['hostedLargeUrl'] as String?; } } return Recipe( name: json['name'] as String?, images: imageUrl, rating: json['rating'] as double?, totalTime: json['totalTime'] as String?, ); } static List<Recipe> recipesFromSnapshot(List? snapshot) { // 校验输入的snapshot是否为null或空列表 if (snapshot == null || snapshot.isEmpty) { return []; } return snapshot.map((data) => Recipe.fromJson(data)).toList(); } @override String toString() { return 'Recipe {name: $name, image: $images, rating: $rating, totalTime: $totalTime}'; } }
额外调试建议
- 在
RecipeApi.getRecipe方法中打印API返回的原始JSON数据,确认是否存在字段缺失、格式异常的情况,便于精准定位问题 - 考虑使用
json_serializable自动生成序列化代码,减少手动编写fromJson时的空指针和类型转换错误风险
内容的提问来源于stack exchange,提问作者Shakuntha Chandimal
相关产品推荐
相关产品推荐

