FutureBuilder如何使用
时间: 2023-07-20 20:45:32 浏览: 44
FutureBuilder 是 Flutter 中用于处理异步数据的 widget,其基本用法如下:
首先,定义一个返回 Future 对象的异步函数,例如:
```dart
Future<String> fetchData() async {
final response = await http.get(Uri.parse('https://example.com/'));
if (response.statusCode == 200) {
return response.body;
} else {
throw Exception('Failed to fetch data');
}
}
```
然后,在 widget 树中使用 FutureBuilder,将异步函数作为 future 参数传入,例如:
```dart
FutureBuilder<String>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data);
} else if (snapshot.hasError) {
return Text('${snapshot.error}');
} else {
return CircularProgressIndicator();
}
},
);
```
在 builder 方法中,根据异步快照的状态(`hasData`、`hasError`、`connectionState` 等)来构建相应的 widget。
以上是 FutureBuilder 的基本用法,你可以根据自己的需求进行进一步的定制。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)