FutureBuilder
is a widget in Flutter for Future
building user interfaces based on the results of . It takes a Future
object and a constructor as parameters.
FutureBuilder
will listen for Future
changes to the object and update the UI accordingly. A loading indicator can be displayed while Future
the is being parsed. Once Future
complete, the build function is called to process the returned data and build the UI based on success or failure status.
Here is FutureBuilder
an example using :
Future<String> fetchData() async {
// 模拟异步调用
await Future.delayed(Duration(seconds: 2));
return "数据加载成功";
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder<String>(
future: fetchData(),
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
// 在等待 Future 完成时显示加载指示器
return CircularProgressIndicator();
} else {
if (snapshot.hasError) {
// 处理错误情况
return Text('错误:${snapshot.error}');
} else {
// 数据已经成功获取
return Text('数据:${snapshot.data}');
}
}
},
);
}
}
In this example, fetchData
a function represents an asynchronous operation that returns a string value Future
. FutureBuilder
Pass this Future
along with a builder function to define how to Future
build the UI based on the different states. In this example, we display a loading indicator while the data is loading, display an error message if there is an error, or display the fetched data if it was fetched successfully.