Flutter异步获取网络数据
使用dio和futurebuilder,异步获取网络数据.在数据加载之前,页面显示加载图标.
代码如下:
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future<String> mockNetworkData() async {
//请求url
var url = 'http://xxx';
try {
Response response = await Dio().get(url);
//print(response);
// print("------------");
// print(response.data.toString());
return response.data.toString();
} catch(e){
print(e);
return '获取数据失败';
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: FutureBuilder<String>(
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 {
// 请求未结束,显示loading
return CircularProgressIndicator();
}
},
),
),
);
}
}
其中,FutureBuilder
会依赖一个Future
,它会根据所依赖的Future
的状态来动态构建自身。
FutureBuilder
构造函数:
FutureBuilder({
this.future,
this.initialData,
@required this.builder,
})
-
future:FutureBuilder依赖的Future,通常是一个异步耗时任务。
-
initialData:初始数据,用户设置默认数据。
-
builder:Widget构建器;该构建器会在Future执行的不同阶段被多次调用,构建器签名如下:
Function (BuildContext context, AsyncSnapshot snapshot)
snapshot会包含当前异步任务的状态信息及结果信息 ,比如可以通过snapshot.connectionState获取异步任务的状态信息、通过snapshot.hasError判断异步任务是否有错误等等,完整的定义可以查看AsyncSnapshot类定义。