Flutter FutureBuilder加载后同时返回空提示与列表问题咨询
问题根源
你当前的错误是把空状态判断逻辑写到了ListView.builder的条目构造逻辑里,只要berichte列表长度大于0,index == 0的分支永远会触发,返回空提示组件,同时符合team条件的其他条目也会渲染卡片,就会出现两个组件同时展示的问题。另外你没有提前对符合条件的有效数据做全局判断,直接就返回了ListView。
修改方案
先在拿到接口返回数据后,先过滤出符合当前team条件的所有有效赛事报告,再根据过滤后的结果判断返回空提示还是列表:
return FutureBuilder<BerichtList>( future: futureBerichte, builder: (context, snapshot) { // 优先处理加载状态 if (snapshot.connectionState == ConnectionState.waiting) { return const AppProgressIndicator(); } // 处理数据加载完成的情况 if (snapshot.hasData) { // 先过滤出符合当前team条件的所有赛事报告 final validBerichte = snapshot.data!.berichte.where((item) => item.team == team).toList(); // 有效数据为空直接返回空提示 if (validBerichte.isEmpty) { return Center( child: Text( "Keine Spielberichte vorhanden", style: TextStyles.body, ), ); } // 有有效数据则渲染列表 return ListView.builder( itemCount: validBerichte.length, itemBuilder: (context, index) { final bericht = validBerichte[index]; return Card( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(15.0), ), elevation: 5, color: Colors.white, child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ Container( padding: const EdgeInsets.symmetric(horizontal: 10), margin: const EdgeInsets.symmetric(vertical: 15), child: Text( DateFormat("dd.MM.yyyy HH:mm").format( DateTime.parse(bericht.spielDatum), ), style: TextStyles.body, ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 10), child: Text( bericht.spiele, style: TextStyles.body, ), ), Container( padding: const EdgeInsets.symmetric(horizontal: 10), margin: const EdgeInsets.only(bottom: 30), child: Text( bericht.bericht, style: TextStyles.body, ), ), ], ), ); }, ); } // 可选:处理加载错误的情况,你可以根据需求调整返回内容 if (snapshot.hasError) { return Center( child: Text("加载失败:${snapshot.error}", style: TextStyles.body), ); } // 兜底状态,正常不会走到这里 return const AppProgressIndicator(); }, );
优化点说明
- 提前过滤有效数据,避免在列表条目构造逻辑里做条件判断,减少多余渲染
- 把空状态判断提到ListView外层,保证空状态和列表只会出现其中一个
- 完善了FutureBuilder的状态判断逻辑,覆盖加载中、加载完成有数据、加载错误的场景,避免出现空白无响应的情况
内容的提问来源于stack exchange,提问作者mame
相关产品推荐
相关产品推荐

