Flutter如何在单页面通过多个FutureBuilder调用多组API?
同页面多分类接口并行拉取实现方案
结合你现有代码结构,有两种可直接落地的实现方式,全程不需要重构原有逻辑:
方案1:分区块独立绑定FutureBuilder(改造成本最低,适配现有结构)
- 你现在的页面本身就是按分类分块布局,只需要给每个分类区块单独配一个FutureBuilder即可。多FutureBuilder不存在冲突,所有接口请求在初始化时就会并行发起,不会互相阻塞。
- 必须规避的踩坑点:不要在build方法的FutureBuilder参数内直接调用接口方法创建Future。否则只要触发组件重建(比如滚动、父组件状态更新),就会重复发起冗余请求。需要把所有Future实例提前在组件初始化阶段创建完成。
- 需要先在你的
WpPostService中补充按分类拉取的方法:
// 扩展现有WpPostService能力 class WpPostService { // 原有最新文章拉取逻辑 Future<List<Post>> getPosts({int perPage = 10}) async { // 保留你原有的接口请求、数据解析逻辑 } // 新增按分类拉取的方法 Future<List<Post>> getPostsByCategory(int categoryId, {int perPage = 5}) async { // 对应WordPress REST API请求路径:/wp-json/wp/v2/posts?categories=$categoryId&per_page=$perPage // 复用原有的接口解析逻辑即可 } }
- 改造后的代码同时解决你现有代码的两个隐患:Column嵌套ListView的溢出问题、内容截取越界崩溃问题:
// 改为Stateful组件以实现Future的提前初始化 class HomePage extends StatefulWidget { static const routeName = 'homepage'; @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { final WpPostService wpPostService = WpPostService(); // 提前初始化所有需要的请求,初始化即并行发起 late Future<List<Post>> latestPostsFuture; late Future<List<Post>> ghazalPostsFuture; late Future<List<Post>> featurePostsFuture; @override void initState() { super.initState(); // 三个接口请求同时发起,无串行等待 latestPostsFuture = wpPostService.getPosts(perPage: 5); ghazalPostsFuture = wpPostService.getPostsByCategory(2, perPage: 5); featurePostsFuture = wpPostService.getPostsByCategory(3, perPage: 5); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( centerTitle: true, title: Text('welcome to LilwaQamar'), ), // 整页滚动容器,解决嵌套ListView的溢出问题 body: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // 最新文章区块 _buildSectionTitle('最新文章'), Container( height: 300, child: FutureBuilder<List<Post>>( future: latestPostsFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } if (snapshot.hasError) return Center(child: Text('内容加载失败')); final posts = snapshot.data ?? []; return ListView( children: posts.map((post) => _buildPostCard(post)).toList(), ); }, ), ), // Ghazals分类区块 _buildSectionTitle('Ghazals'), Container( height: 300, child: FutureBuilder<List<Post>>( future: ghazalPostsFuture, builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator()); } if (snapshot.hasError) return Center(child: Text('内容加载失败')); final posts = snapshot.data ?? []; return ListView( children: posts.map((post) => _buildPostCard(post)).toList(), ); }, ), ), // 其他分类区块按需补充即可,结构完全复用 ], ), ), ); } // 抽离公共的文章卡片组件,减少重复代码 Widget _buildPostCard(Post post) { return Card( elevation: 6, margin: EdgeInsets.all(10.0), child: ListTile( title: Html( data: post.title.rendered, defaultTextStyle: GoogleFonts.lato( textStyle: TextStyle( color: Colors.black, letterSpacing: .5, fontSize: 19), ), ), subtitle: Html( data: _buildExcerpt(post.content.rendered, 73), defaultTextStyle: GoogleFonts.lato( textStyle: TextStyle( color: Colors.black54, letterSpacing: .5, fontSize: 16), ), ), onTap: () { Navigator.push( context, MaterialPageRoute( builder: (context) => PostDetaislPage(post: post), ), ); }, ), ); } // 新增摘要截断逻辑,解决原代码截取长度超出字符串范围的崩溃问题 String _buildExcerpt(String content, int maxLength) { if (content.length <= maxLength) return content; return content.substring(0, maxLength) + '..'; } // 抽离分类标题组件 Widget _buildSectionTitle(String title) { return Padding( padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), child: Text( title, style: GoogleFonts.lato(fontSize: 22, fontWeight: FontWeight.bold), ), ); } }
方案2:Future.wait统一并行拉取(加载体验更统一)
如果不希望页面出现“某一分类加载完先显示内容、另一分类还在转圈”的割裂感,可以把所有需要拉取的分类接口用Future.wait打包并行执行,等所有数据全部返回后再统一渲染页面:
- 初始化逻辑替换为:
late Future<List<List<Post>>> combinedPostsFuture; @override void initState() { super.initState(); // 按顺序传入所有需要的接口请求,总耗时等于最慢的单个接口耗时 combinedPostsFuture = Future.wait([ wpPostService.getPosts(perPage: 5), wpPostService.getPostsByCategory(2, perPage: 5), wpPostService.getPostsByCategory(3, perPage: 5), ]); }
- 渲染逻辑中通过一个FutureBuilder统一获取所有结果,按请求顺序对应到各个分类区块即可,这种方式可以在页面一开始只显示一个全局加载动画,所有数据准备完成后一次性展示全部内容。
内容的提问来源于stack exchange,提问作者Mayanktaker
相关产品推荐
相关产品推荐

