今天来学学flutter的网络请求

Dio插件的使用

dio 是 Flutter 里最常用的 HTTP 网络请求库之一,很多项目都会用它替代原生的 http 包,因为它功能更完整

(话说看到这个Dio我就想起了某个埃及艳妇 狗头狗头狗头)

OK回归正题

首先根目录执行

1
flutter pub add dio

打开你的pubspec.yaml文件

可以看到这个

1
2
3
4
5
6
7
8
dependencies:
flutter:
sdk: flutter

# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
dio: ^5.9.2 #dio下载完成

基本使用

Dio().get(地址).then().catchError()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

void main() {
runApp(MaterialApp(home: HomePage()));
}

class HomePage extends StatefulWidget {
const HomePage({super.key});

@override
State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
String text = "点击获取数据";

void getData() async {
Response response = await Dio().get('https://genshin.hoyoverse.com/en/');

setState(() {
text = response.data.toString();
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("原神网页"), centerTitle: true),

body: Center(
child: SingleChildScrollView(
child: Padding(
padding: EdgeInsets.all(20),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: getData,
child: Text("获取网页", style: TextStyle(fontSize: 18)),
),

SizedBox(height: 20),

Text(text, textAlign: TextAlign.center),
],
),
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: getData,
child: Icon(Icons.refresh),
),
);
}
}
image-20260517163247875