Flutter新手网络JSON数据无法显示问题排查及代码修正
问题排查与代码修正
核心错误原因
- 类型不匹配:你的
ebdetails函数声明返回Future<List<String>>,但接口返回的是包含对象的数组(List<Map<String, dynamic>>),类型转换失败直接触发snapshot.hasError,显示"Data Error"。 - 未处理HTTP响应状态:未校验请求是否成功(比如状态码200),直接解析响应体可能引发异常。
- FutureBuilder使用不当:
future参数直接写在build方法中,每次组件重建都会重新发起网络请求。 - 数据展示错误:即使数据获取成功,直接打印数组中的对象会显示
Instance of 'xxx',无法展示实际数据。
修正后的完整代码
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:http/http.dart' as http; void main() { runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return const MaterialApp( home: Mydata(), ); } } // 定义数据模型,对应接口返回的对象结构 class EbData { final int id; final double rCurrent; final double yCurrent; final double bCurrent; final int rVoltage; final int yVoltage; final int bVoltage; final int upsVoltage; final double upsCurrent; final int upsBattery; EbData({ required this.id, required this.rCurrent, required this.yCurrent, required this.bCurrent, required this.rVoltage, required this.yVoltage, required this.bVoltage, required this.upsVoltage, required this.upsCurrent, required this.upsBattery, }); // 从Map转换为EbData对象 factory EbData.fromJson(Map<String, dynamic> json) { return EbData( id: json['id'], rCurrent: json['R_Current'], yCurrent: json['Y_Current'], bCurrent: json['B_Current'], rVoltage: json['R_Voltage'], yVoltage: json['Y_Voltage'], bVoltage: json['B_Voltage'], upsVoltage: json['UPS_Voltage'], upsCurrent: json['UPS_Current'], upsBattery: json['UPS_Battery'], ); } } class Mydata extends StatefulWidget { const Mydata({super.key}); @override State<Mydata> createState() => _MydataState(); } class _MydataState extends State<Mydata> { // 初始化future,避免每次build重复请求 late Future<List<EbData>> _ebDetailsFuture; @override void initState() { super.initState(); _ebDetailsFuture = ebdetails(); } Future<List<EbData>> ebdetails() async { final response = await http.get(Uri.parse('http://117.247.181.113:8000/eb/1/')); // 校验响应状态码,仅在成功时解析数据 if (response.statusCode == 200) { List<dynamic> jsonList = jsonDecode(response.body); // 将每个Map转换为EbData对象 return jsonList.map((json) => EbData.fromJson(json)).toList(); } else { // 请求失败时抛出异常,触发FutureBuilder的错误状态 throw Exception('请求失败,状态码:${response.statusCode}'); } } @override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, appBar: AppBar( elevation: 0, centerTitle: true, title: const Text( 'Json Datas', style: TextStyle( color: Colors.black, ), ), backgroundColor: Colors.white, ), body: FutureBuilder<List<EbData>>( future: _ebDetailsFuture, builder: (context, snapshot) { if (snapshot.hasError) { return Center( // 显示具体错误信息,便于调试 child: Text('数据加载失败:${snapshot.error}'), ); } else if (snapshot.hasData) { return ListView.builder( padding: const EdgeInsets.all(16), itemCount: snapshot.data!.length, itemBuilder: (context, i) { EbData data = snapshot.data![i]; // 展示具体的属性值 return Card( child: Padding( padding: const EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('ID: ${data.id}'), const SizedBox(height: 8), Text('R相电流: ${data.rCurrent}A'), Text('Y相电流: ${data.yCurrent}A'), Text('B相电流: ${data.bCurrent}A'), const SizedBox(height: 8), Text('R相电压: ${data.rVoltage}V'), Text('Y相电压: ${data.yVoltage}V'), Text('B相电压: ${data.bVoltage}V'), const SizedBox(height: 8), Text('UPS电压: ${data.upsVoltage}V'), Text('UPS电流: ${data.upsCurrent}A'), Text('UPS电池电量: ${data.upsBattery}%'), ], ), ), ); }, ); } else { return const Center(child: CircularProgressIndicator()); } }, ), ); } }
关键修改说明
- 创建数据模型
EbData:将JSON对象映射为强类型对象,便于安全访问属性。 - 修正异步函数返回类型:改为
Future<List<EbData>>,匹配接口返回的数据结构。 - 校验HTTP响应状态:仅在状态码200时解析数据,否则抛出异常。
- 优化FutureBuilder使用:将
future初始化在initState中,避免重复请求。 - 优化数据展示:使用Card和Column展示具体属性值,替代直接打印对象。
内容的提问来源于stack exchange,提问作者Devendiran
相关产品推荐
相关产品推荐

