实现步骤
- 添加依赖
dio: 3.0.7
- 发起网络请求
void _initAsync() async {
Response response;
Dio dio = new Dio();
response = await
dio.get("https://gitee.com/cxyzy1/flutter_network_demo/raw/master/data.txt");
}
界面效果
主要代码
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter网络请求demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String content = "loading...";
@override
void initState() {
super.initState();
_initAsync();
}
void _initAsync() async {
Response response;
Dio dio = new Dio();
response = await dio.get("https://gitee.com/cxyzy1/flutter_network_demo/raw/master/data.txt");
setState(() {
content = response.data.toString();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'$content',
)
],
),
),
);
}
}
完整源代码
https://gitee.com/hspbc/flutter_network_demo