Flutter API多数据列表展示求助:ListView.Builder使用报错
解决Flutter中展示API返回的地区数据列表问题
你的数据模型和请求逻辑没问题,问题出在页面没有正确处理异步数据并构建列表。下面是修改后的完整页面代码,直接替换原有代码即可:
import 'package:covidapp/models/covidModel.dart'; import 'package:flutter/material.dart'; import 'package:covidapp/services/fetchCountry.dart'; class CovidPage extends StatefulWidget { const CovidPage({Key? key}) : super(key: key); @override State<CovidPage> createState() => _CovidPageState(); } class _CovidPageState extends State<CovidPage> { late Future<CovidModel> futureCountry; @override void initState() { super.initState(); futureCountry = FetchCountry().fetchData(); } @override Widget build(BuildContext context) { return Scaffold( body: SafeArea( child: Container( width: double.infinity, height: double.infinity, color: const Color.fromRGBO(255, 246, 234, 1), child: Column( children: [ SizedBox(height: MediaQuery.of(context).size.height * 0.03), const Text( 'Covid Data', textAlign: TextAlign.center, style: TextStyle( fontSize: 29, fontWeight: FontWeight.w700, color: Color.fromARGB(255, 112, 108, 112), ), ), // 用Expanded包裹ListView,避免布局溢出问题 Expanded( child: FutureBuilder<CovidModel>( future: futureCountry, builder: (context, snapshot) { // 处理加载状态 if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } // 处理错误状态 if (snapshot.hasError) { return Center(child: Text('加载失败: ${snapshot.error}')); } // 数据加载完成且不为空 if (snapshot.hasData && snapshot.data!.states != null) { final states = snapshot.data!.states!; return ListView.builder( padding: const EdgeInsets.all(16), itemCount: states.length, itemBuilder: (context, index) { final stateData = states[index]; return Card( margin: const EdgeInsets.only(bottom: 12), child: Padding( padding: const EdgeInsets.all(16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( stateData.state ?? '未知地区', style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), const SizedBox(height: 8), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Text('确诊: ${stateData.cases ?? 0}'), Text('治愈: ${stateData.recoveries ?? 0}'), Text('死亡: ${stateData.deaths ?? 0}'), Text('累计: ${stateData.total ?? 0}'), ], ), ], ), ), ); }, ); } // 无数据状态 return const Center(child: Text('暂无数据')); }, ), ), ], ), ), ), ); } }
关键修改点说明:
- 类名规范:将
covidPage改为CovidPage,符合Dart大驼峰命名规范 - FutureBuilder处理异步数据:用来监听
futureCountry的状态,分别处理加载中、错误、数据加载完成三种状态 - Expanded包裹ListView:解决Column中ListView无约束高度导致的布局溢出问题,让列表占满页面剩余空间
- 空安全处理:对可空的
states和地区数据字段(如state、cases)做了空值判断,避免空指针异常 - 自定义列表项:用Card替代简单的ListTile,让数据展示更清晰美观
内容的提问来源于stack exchange,提问作者Harun Demirkaya
相关产品推荐
相关产品推荐

