Flutter执行json.decode时触发ui_dart_state.cc(198)错误求助
问题分析与解决方案
核心代码错误
你的代码存在一个致命逻辑错误:用response.hashCode == 200判断HTTP响应状态。hashCode是对象的哈希标识,和HTTP状态码没有任何关联,正确写法应为response.statusCode == 200。这个错误会导致你错误处理非200状态的响应,进而触发JSON解析异常。
修正后的完整代码
import 'dart:convert'; import 'package:http/http.dart' as http; class PlanosRepository { Future<List<PlanosModel>> load() async { final client = http.Client(); try { final uri = Uri.parse('http://localhost:3001/sales/lista_planos'); final response = await client.get(uri); // 修正:用statusCode判断HTTP响应状态 if (response.statusCode == 200) { try { // 捕获JSON解析异常 final body = json.decode(response.body); // 确保返回数据是数组类型再执行映射 if (body is List) { List<PlanosModel> planos = body.map((json) => PlanosModel.fromJson(json)).toList(); return planos; } else { throw Exception('后端返回的不是JSON数组格式'); } } on FormatException catch (e) { throw Exception('JSON解析失败:${e.message}'); } } else { throw Exception('请求失败,状态码:${response.statusCode}'); } } catch (e) { throw Exception('网络请求异常:${e.toString()}'); } finally { client.close(); } } }
额外排查步骤
验证后端返回格式:确认
http://localhost:3001/sales/lista_planos返回标准JSON数组,示例格式:[{"id":1,"nome":"Plano Basico"},{"id":2,"nome":"Plano Premium"}]如果返回的是嵌套数组(比如
{"dados": [...]}),需先提取对应字段:final List body = json.decode(response.body)['dados'];检查PlanosModel解析逻辑:确保
fromJson方法与后端返回的JSON字段完全匹配,包括字段名大小写、数据类型(比如数字类型不能用String接收)。示例模型:class PlanosModel { final int id; final String nome; PlanosModel({required this.id, required this.nome}); factory PlanosModel.fromJson(Map<String, dynamic> json) { return PlanosModel( id: json['id'] as int, nome: json['nome'] as String, ); } }查看完整错误日志:
ERROR:flutter/lib/ui/ui_dart_state.cc(198)是Dart状态异常的通用提示,需查看日志后续的具体错误信息(如FormatException、TypeError),才能精准定位问题。
内容的提问来源于stack exchange,提问作者Nukeer
相关产品推荐
相关产品推荐

