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

Flutter中使用JsonFormat解析API数据时空值调用异常求助

解决Flutter解析JSON时"The method '[]' was called on null"异常

核心原因

这个错误本质是你尝试对null值使用数组/Map的下标访问符[]。常见触发场景:

  • API返回的JSON结构和你预期不符,某个层级的字段不存在或为null
  • 网络请求未完成就提前解析数据(比如在initState里同步处理异步请求结果)
  • 字段名拼写错误(比如API返回temp你写成temperature)

针对性修复方案

1. 逐层校验JSON节点,避免链式访问

不要直接写responseData['weather'][0]['temp']这类链式代码,每一层都要做null判断:

// 错误示例:直接链式访问,某一层为null就会报错
var temperature = jsonData['main']['temp'];

// 正确示例:逐层校验,兜底赋值
var mainData = jsonData['main'];
double temperature = 0.0;
if (mainData != null) {
  temperature = (mainData['temp'] as num?)?.toDouble() ?? 0.0;
}
setState(() {
  _temp = temperature;
});

2. 确保网络请求完成后再解析

异步请求必须在await或then回调里处理解析,不要在请求未完成时访问结果:

// 正确示例:用await等待异步请求结果
Future<void> fetchWeatherData() async {
  try {
    final response = await http.get(Uri.parse(apiUrl));
    if (response.statusCode == 200) {
      final jsonData = jsonDecode(response.body);
      // 逐层安全解析
      double temperature = jsonData['main']?['temp'] ?? 0.0;
      setState(() {
        _temp = temperature;
      });
    } else {
      setState(() => _temp = 0.0);
    }
  } catch (e) {
    setState(() => _temp = 0.0);
  }
}

3. 使用JSON序列化工具(推荐)

手动解析易出错,用官方推荐的json_serializable包自动生成安全解析代码:

  1. 添加依赖到pubspec.yaml:
dependencies:
  json_annotation: ^4.8.1

dev_dependencies:
  build_runner: ^2.4.4
  json_serializable: ^6.7.0
  1. 定义实体类并添加注解:
import 'package:json_annotation/json_annotation.dart';

part 'weather.g.dart';

@JsonSerializable()
class Weather {
  final Main? main;

  Weather({this.main});

  factory Weather.fromJson(Map<String, dynamic> json) => _$WeatherFromJson(json);
}

@JsonSerializable()
class Main {
  final double? temp;

  Main({this.temp});

  factory Main.fromJson(Map<String, dynamic> json) => _$MainFromJson(json);
}
  1. 运行生成命令:
flutter pub run build_runner build
  1. 安全解析数据:
final weather = Weather.fromJson(jsonData);
double temperature = weather.main?.temp ?? 0.0;

4. 调试技巧

  • 先打印完整的jsonData,确认API返回的实际结构,核对字段名和层级是否符合预期
  • 用Flutter DevTools的Network面板查看请求返回的原始数据,排查结构差异

内容的提问来源于stack exchange,提问作者Emmanuel Armoo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 14:30:51