【英文】Flutter发送请求

Preface

Flutter Request Learning Notes

Preparation

Add Dependencies

1
flutter pub add http

Define Response Entity Class

  • Map the expected response content to the response entity class
lib/models/user.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class User {
final String username;
final String password;

const User({
required this.username,
required this.password,
});

factory User.fromJson(Map<String, dynamic> json) {
return User(
username: json['username'],
password: json['password'],
);
}
}

Send Requests

Send GET Requests

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:mobile/models/user.dart';

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

@override
State<App> createState() => _AppState();
}

class _AppState extends State<App> {

// 1. Define the future object used to handle the response
Future<User>? _futureUser;

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Text Content"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () {
// 2. Whenever the button is clicked, send a request and update the data in the future object
setState(() {
_futureUser = getAccount();
});
},
child: const Text("Login"),
),
Container(
// 3. Render the Container based on the data in the future object. If there is no response, return null; if there is a response, return the response data
child: (_futureUser == null) ? null : buildFutureBuilder(),
)
],
),
),
),
);
}

// 3. Render the Container based on the data in the future object
FutureBuilder<User> buildFutureBuilder() {
return FutureBuilder<User>(
future: _futureUser,
builder: (context, snapshot) {
if (snapshot.hasData) {
// 3.1. Get the attribute values of the entity object through the future object
return Text("${snapshot.data!.username}\n${snapshot.data!.password}");
} else if (snapshot.hasError) {
// 3.2. Failed to get the entity object through the future object
return Text('${snapshot.error}');
}
return const CircularProgressIndicator();
},
);
}
}

// 2. Send a request
Future<User> getAccount() async {
final response = await http.get(
// 2.1. URL path of the request
Uri.parse('http://192.168.0.23:8080/api'),
);
// 2.2. After receiving the response, handle the data based on different response status codes
if (response.statusCode == 200) {
// 2.3. If the response data is successfully obtained, convert the JSON formatted string into an entity object
return User.fromJson(jsonDecode(response.body));
}
// 2.4. If the response data fails to be obtained, throw an exception
throw Exception('Request failed');
}

Send POST Requests

1
2
3
4
5
6
7
8
9
Future<User> getAccount() async {
final response = await http.post(
Uri.parse('http://192.168.0.23:8080/api'),
);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
}
throw Exception('Request failed');
}

Pass Parameters in the Request Body

1
2
3
4
5
6
7
8
9
10
11
12
13
Future<User> getAccount() async {
final response = await http.post(
Uri.parse('http://192.168.0.23:8080/api'),
// Pass parameters in the request body
body: jsonEncode(<String, String>{
"key": "value",
}),
);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
}
throw Exception('Request failed');
}

Set Request Headers

1
2
3
4
5
6
7
8
9
10
11
12
13
Future<User> getAccount() async {
final response = await http.post(
Uri.parse('http://192.168.0.23:8080/api'),
// Set request headers
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
},
);
if (response.statusCode == 200) {
return User.fromJson(jsonDecode(response.body));
}
throw Exception('Request failed');
}

Completion

References

Flutter Official Documentation