Flutter 处理异步操作并根据异步操作状态动态构建界面的方法FutureBuilder

概述

当界面的内容需要依靠网络请求的数据,就需要处理苦恼的,状态是空,非空的逻辑了,不然页面构建可能会报错,而FutureBuilder提供了一个非常好的解决方法,直接看代码

代码

异步操作函数

即网络请求函数(通常情况下)

Dart 复制代码
Future<List<String>> fetchStringList() async {
  return Future.delayed(Duration(seconds: 2), () {
    // 模拟网络请求
    return ['Item 1', 'Item 2', 'Item 3'];
  });
}

widget构建部分

Dart 复制代码
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('FutureBuilder Example'),
        ),
        body: Center(
          child: FutureBuilder<List<String>>(
            future: fetchStringList(), // Future函数
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                // 数据还在加载中,显示一个加载指示器
                return CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              } else {
                return ListView.builder(
                  itemCount: snapshot.data!.length,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Text(snapshot.data![index]),
                    );
                  },
                );
              }
            },
          ),
        ),
      ),
    );
  }
}

可以看出来,这为需要异步操作的页面提供了更好的构建页面方式。

相关推荐
bksczm34 分钟前
Redis Cluster 分片集群详解:槽路由、故障判定与扩缩容
数据库·redis·分布式
郝学胜-神的一滴1 小时前
Effective Python 条款35:用类封装替代生成器异常注入
开发语言·人工智能·python·金融·pandas·scikit-learn·matplotlib
火山引擎和TA的超级拍档们1 小时前
产品情报局 11 | AI 数据湖 LAS:打造大模型时代多模态数据底座
前端·后端
JavaGuide1 小时前
Gemini 真的变强了,写代码做视频的能力接近 Claude Opus5.5 了!
前端·ai编程
niceyayale1 小时前
WebRTC 延迟怎么调试:从 ICE 到 jitter buffer 的六个观测点
前端
aleimu1 小时前
Windows 11 右键打开 Cmder 2.0:从找不到菜单到默认使用 Cmder
前端·人工智能·后端
tryCbest2 小时前
Vue系列——第 20 篇:Vue Router 4——路由管理完全指南(上)
前端·javascript·vue.js
feixing_fx2 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
wuyk5552 小时前
Python办公自动化-第02讲-Excel文件认知与四大库选型
开发语言·python·excel
一条破秋裤2 小时前
【1115】【多线程】【笔记】
前端·chrome·笔记