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]),
                    );
                  },
                );
              }
            },
          ),
        ),
      ),
    );
  }
}

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

相关推荐
王cb1 天前
WinRT Server and Client c#
开发语言·c#
lichenyang4531 天前
AI 聊天从纯文本到结构化卡片:SSE done 帧携带 card + 历史记录卡片恢复实战
前端
Selina K1 天前
C中日历时间转换
c语言·开发语言
周末也要写八哥1 天前
数据库安装 | SQL Server2022安装教程及网盘下载地址
数据库
故渊at1 天前
第二板块:Android 四大组件标准化学理 | 第六篇:四大组件架构总论与 Manifest 规范
android·架构·zygote·manifest·四大组件
怪我冷i1 天前
zig语言学习笔记——heap-memory
开发语言·golang·zig
李燚1 天前
erlang_migrate 架构拆解:behaviour 驱动的多数据库迁移引擎
数据库·postgresql·架构·erlang·migrate·behaviour·erlang_migrate
梦曦i1 天前
@meng-xi/vite-plugin v0.1.5:告别手动 import,精简工具层
前端
梦曦i1 天前
Vite 0.1.6重磅更新:智能导入+路由安全
前端
Jinkxs1 天前
PostgreSQL - 全文检索的开启与基础使用
数据库·postgresql·全文检索