36 网络操作
1.源代码
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool loading = false;
String text = "";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100),
child: RaisedButton(
child: Text("获取百度首页"),
onPressed: loading ? null : () async {
setState(() {
loading = true;
text = "正在请求...";
});
try {
Dio dio = new Dio();
Response response=await dio.get("https://www.baidu.com/");
text = response.data;
} catch (e) {
text = "请求失败:$e";
} finally {
setState(() {
loading = false;
});
}
}
),
),
Builder(builder: (context){
return Container(
width: MediaQuery
.of(context)
.size
.width - 50.0,
child: Text(text)
);
})
],
),
),
),
),
);
}
}
2.引用
dio: 2.1.7

3.解释源代码
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool loading = false;
String text = "";
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: ConstrainedBox(
constraints: BoxConstraints.expand(),
child: SingleChildScrollView(
child: Column(
children: <Widget>[
Padding(
padding: EdgeInsets.only(top: 100),
child: RaisedButton(
child: Text("获取百度首页"),
onPressed: loading ? null : () async {
setState(() {
loading = true;
text = "正在请求...";
});
try {
Dio dio = new Dio();
Response response=await dio.get("https://www.baidu.com/");
text = response.data;
} catch (e) {
text = "请求失败:$e";
} finally {
setState(() {
loading = false;
});
}
}
),
),
Builder(builder: (context){
return Container(
width: MediaQuery
.of(context)
.size
.width - 50.0,
child: Text(text)
);
})
],
),
),
),
),
);
}
}
4.效果图
