widget名字:
FutureBuilder: async
功能:
返回future类型的数据,用来处理网络等需要时间消耗的操作,并可以判断该过程的是否是否有,还是在获取的过程出现错误等操作;FutureBuilder 继承StatefulWidget,需要在StatefulWidget 里面使用
<1>
const FutureBuilder({
super.key,
this.future,// future 方法
this.initialData,//初始吗,默认的数据
required this.builder,//必须要的函数,返回widget
}) : assert(builder != null);
<2>
snapdata.connectionState 数据的状态,总共有四种:
1. none, // 无
2.waiting,//等待中
3.active, //运行中
4.done,//完成,有异常也会完成
使用实例和代码:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
late Future<String> _getname;
Future<String> doone() {
return Future.delayed(const Duration(seconds: 3)).then((value) => 'JACK');
}
void initState() {
// TODO: implement initState
super.initState();
_getname = doone();
}
Widget build(BuildContext context) {
print('i am do build MAIN');
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder(
initialData: 'MY NAME IS GUESS',//数据还是none的时候会默认显示该数据
//future method
future: _getname,
builder: (context, snapdata) {
//启动之后,会发现这边被执行了两次
print('i am do build');
String txt_info = '';
if (snapdata.connectionState == ConnectionState.done) {
//数据拉取完成的状态
if (snapdata.hasError) {
//有错误
txt_info = '数据有错误${snapdata.error}';
} else {
//数据过程没有错误
txt_info = '数据内容是${snapdata.data}';
}
} else {
//数据还完成操作
txt_info = '数据获取中......';
}
return Text(txt_info);
})),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.refresh_sharp),
onPressed: () {
setState(() {});
},
),
// This trailing comma makes auto-formatting nicer for build methods.
);
}
}