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

Flutter中Item Builder仅渲染1条天气预报而非7条的问题

问题排查与解决

核心排查方向

先确认数据是否真的返回了7天预报,再逐步定位问题:

  1. 验证返回数据的长度
    在snapshot.hasData分支中添加打印代码,查看实际获取到的预报天数:
if (snapshot.hasData) {
  WeatherModel? dailyUpdate = snapshot.data;
  print('获取到的预报天数:${dailyUpdate?.forecast?.forecastday?.length}');
  // 原有代码...
}

针对不同结果的解决方法

情况1:打印结果为1

这说明API请求只返回了1天数据,问题出在fetchWeather函数的请求参数上。WeatherAPI默认返回1天预报,必须显式添加days=7参数才会返回7天数据。检查weatherHelper.dart中的fetchWeather函数,确保请求URL包含该参数:

// 示例正确请求URL格式
final url = Uri.parse('http://api.weatherapi.com/v1/forecast.json?key=你的密钥&q=${searchText}&days=7');

情况2:打印结果为7

这说明数据模型解析存在问题,导致forecastday列表没有被正确解析。检查weatherModel.dart中的Forecast类,确保forecastday字段被正确序列化为List:

class Forecast {
  List<Forecastday>? forecastday;

  Forecast({this.forecastday});

  factory Forecast.fromJson(Map<String, dynamic> json) {
    // 确保将json数组转为Forecastday列表
    final forecastdayList = (json['forecastday'] as List)
        .map((item) => Forecastday.fromJson(item))
        .toList();
    return Forecast(forecastday: forecastdayList);
  }
}

额外优化建议

原组件为StatelessWidget,每次重绘都会重新发起API请求,可能导致数据不稳定。建议改为StatefulWidget,在initState中初始化请求:

class DailyUpdate extends StatefulWidget {
  const DailyUpdate({super.key, required this.searchText});
  final String searchText;

  @override
  State<DailyUpdate> createState() => _DailyUpdateState();
}

class _DailyUpdateState extends State<DailyUpdate> {
  late final Future<WeatherModel?> _weatherFuture;
  final weatherClass weatherObj = weatherClass();

  @override
  void initState() {
    super.initState();
    _weatherFuture = weatherObj.fetchWeather(widget.searchText);
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: _weatherFuture,
      builder: (context, snapshot) {
        // 原有builder逻辑
      },
    );
  }
}

内容的提问来源于stack exchange,提问作者Mr. Anonymous

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 16:12:48