flutter futurebuilder代码
时间: 2023-05-29 18:01:12 浏览: 128
下面是一个基本的Flutter FutureBuilder示例代码:
```
import 'package:flutter/material.dart';
class ExampleFutureBuilder extends StatefulWidget {
@override
_ExampleFutureBuilderState createState() => _ExampleFutureBuilderState();
}
class _ExampleFutureBuilderState extends State<ExampleFutureBuilder> {
// Future that simulates data loading
Future<String> _futureData() async {
await Future.delayed(Duration(seconds: 3));
return "Data returned from future!";
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("FutureBuilder Example"),
),
body: FutureBuilder<String>(
future: _futureData(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text("No data yet.");
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
case ConnectionState.done:
if (snapshot.hasError) {
return Text("Error: ${snapshot.error}");
} else if (!snapshot.hasData) {
return Text("No data retrieved.");
} else {
return Center(child: Text(snapshot.data!));
}
}
},
),
);
}
}
```
这是一个简单的页面,它使用FutureBuilder小部件来获取和显示数据。它使用一个Future方法 `_futureData()` 来模拟加载数据,然后使用FutureBuilder小部件来侦听和显示Future。在 `builder` 函数中,它检查 `connectionState`,并根据需要返回不同的小部件。
如果 `connectionState` 是 `none`,它会返回 "No data yet.";如果是 `waiting`,它会返回一个旋转的进度指示器;如果是 `active` 或 `done`,则会检查 `hasError` 和 `hasData`。如果存在错误,则它会返回错误消息,否则它将返回数据。
阅读全文