Flutter调用SWAPI遇空值异常:非空字段也为空的解决需求
Flutter调用SWAPI处理空数组字段的问题解决
问题根源
你的问题主要出在两个地方:
- 字段拼写错误:代码里的
vehcles和starsips是拼写错误,正确的API返回字段名应为vehicles和starships。访问不存在的属性会返回null,若你的数据模型中这两个字段是List类型,直接赋值null会触发运行时异常,中断setState内的赋值流程,导致后续species、created等字段未被赋值,最终显示为null。 - 空数组的空安全处理:API返回的空数组
[]本身是合法值,但如果未做兜底处理,结合拼写错误的null值,会直接引发异常阻断流程。
解决方案
1. 修正拼写错误
确保访问正确的API返回字段名,避免因属性不存在导致的null值。
2. 添加空安全兜底
对列表字段使用空值合并运算符??,当API返回null(或因拼写错误得到null)时,自动赋值为空列表,避免异常。
修正后的代码:
Future<dynamic> getSwData() async { return await MyStarWarsService().getDataFromSWApi().then((value) { if (value != null) { setState(() { name = value.name!; height = value.height!; mass = value.mass!; birth_year = value.birth_year!; eye_color = value.eye_color!; films = value.films!; gender = value.gender!; hair_color = value.hair_color!; homeworld = value.homeworld!; skin_color = value.skin_color!; // 修正拼写错误+空列表兜底 vehicles = value.vehicles ?? []; starships = value.starships ?? []; species = value.species!; created = value.created!; edited = value.edited!; url = value.url!; }); return value; } }).catchError((_) { throw Exception("Exception is caught"); }); }
额外优化建议
- 既然已通过
if(value != null)判断value不为null,内部的value!强制解包可以去掉,直接使用value.name即可(若数据模型字段为可空类型,可根据需求用??设置默认值)。 - 建议使用强类型数据模型(比如通过
json_serializable生成)替代dynamic类型,编译阶段就能发现拼写错误,避免运行时异常。
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

