Flutter FutureBuilder使用问题:服务器数据拉取成功,ListView无报错返回空
问题排查与修复方案
你代码里存在2个核心导致ListView不显示的问题,同时附带可优化的细节:
核心问题
- 缺少return关键字:你在
snapshot.hasData的判断分支中实例化了ListView.builder,但没有将它作为Widget返回,该分支实际返回空值,所以没有内容渲染也不会触发报错。 - 下标取值错误:
snapshot.data['index']['title']中将变量index加了引号,会被识别为固定字符串键"index",而非遍历的动态下标,永远取不到对应值。
优化点
- 错误提示分支不要写死字符串
snapshot.error,要输出实际的错误对象,方便排查问题 - 建议给异步方法、
AsyncSnapshot添加泛型约束,避免隐式类型隐患 - 目前写法每次组件重绘都会重新发起网络请求,建议改为StatefulWidget在initState中预存future对象,避免重复请求
修正后代码
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:phc_gps_sms/constant.dart'; import 'package:phc_gps_sms/network_utils/api.dart'; class TipsCarousel extends StatelessWidget { const TipsCarousel({ Key? key, }) : super(key: key); // 建议指定返回类型,这里假设接口返回的是List<Map> Future<List<dynamic>> _getGuidlines() async { var res = await Network().getData('/guidlines'); var body = json.decode(res.body)['guidlines']; print(body); return body; } @override Widget build(BuildContext context) { return Column( children: <Widget>[ Padding( padding: const EdgeInsets.symmetric(horizontal: 20.0), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ const Text( 'Tips', style: TextStyle( fontSize: 22.0, fontWeight: FontWeight.bold, ), ), GestureDetector( onTap: () => print('See All'), child: Text( 'See All', style: TextStyle( color: kPrimaryColor, fontSize: 16.0, fontWeight: FontWeight.w600, letterSpacing: 1.0), ), ) ], ), ), Container( height: 300.0, child: FutureBuilder<List<dynamic>>( future: _getGuidlines(), builder: (BuildContext context, AsyncSnapshot<List<dynamic>> snapshot) { if (snapshot.hasError) { return Center( // 输出实际错误信息 child: Text(snapshot.error.toString()), ); } if (snapshot.hasData) { // 补充return关键字 return ListView.builder( scrollDirection: Axis.horizontal, itemCount: snapshot.data!.length, itemBuilder: (BuildContext context, int index) { // 去掉index的引号,使用变量取值 return Text(snapshot.data![index]['title']); }, ); } return const Center( child: CircularProgressIndicator(), ); }, ), ) ], ); } }
内容的提问来源于stack exchange,提问作者Jade
相关产品推荐
相关产品推荐

