import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
// configLoading();
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(home: HomeBody());
}
}
class HomeBody extends StatelessWidget {
const HomeBody({ Key? key }) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title:const Text("FutureBuilder"),
),
body: Container(
alignment: Alignment.center,
height: 300,
child: FutureBuilder(
future: mockNetworkData(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
// 请求失败,显示错误
return Text("Error: ${snapshot.error}");
} else {
// 请求成功,显示数据
return Text("Contents: ${snapshot.data}");
}
} else {
return CircularProgressIndicator();
}
})));
}
Future<String> mockNetworkData() async {
return Future.delayed(Duration(seconds: 10), () => "我是从互联网上获取的数据");
}
}
FutureBuilder是接收Future异步更新UI的控件
最新推荐文章于 2024-11-07 09:11:54 发布