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

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('暂无数据'));
                  },
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

关键修改点说明:

  1. 类名规范:将covidPage改为CovidPage,符合Dart大驼峰命名规范
  2. FutureBuilder处理异步数据:用来监听futureCountry的状态,分别处理加载中、错误、数据加载完成三种状态
  3. Expanded包裹ListView:解决Column中ListView无约束高度导致的布局溢出问题,让列表占满页面剩余空间
  4. 空安全处理:对可空的states和地区数据字段(如state、cases)做了空值判断,避免空指针异常
  5. 自定义列表项:用Card替代简单的ListTile,让数据展示更清晰美观

内容的提问来源于stack exchange,提问作者Harun Demirkaya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 21:36:29