dio
- 我的后端封装了一个result结果类,返回给前端一个json数据,
public class Result<T> implements Serializable{
private String statusCode = ResultType.SUCCESS.getCode();
private String message = ResultType.SUCCESS.getName();
private T data = null;
- 在http请求方面我用的是dio库,使用要先在
pubspec.yaml
引入包
# dio-网络请求
dio: ^4.0.0
-
由于我还使用了getx,所以在使用引入时记得加上as,因为它们两个库中都有response
import 'package:get/get.dart'; import 'package:dio/dio.dart' as dio;
-
我在调用了api接口后,根据response.data里的statusCode反馈不同状态
import 'package:flutter_english_hub/model/User.dart';
import 'package:flutter_english_hub/service/api_service.dart';
import 'package:flutter_english_hub/service/storage_service.dart';
import 'package:get/get.dart';
import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.dart';
class AuthService extends GetxService {
final ApiService apiService = Get.find<ApiService>();
final StorageService storageService = Get.find<StorageService>();
// 存储当前登录用户信息
var user = Rxn<User>();
// 监听登录状态
RxBool isAuthenticated = false.obs;
void showFeedback(String type, String message, Color backgroundColor) {
Get.snackbar(type, message,
snackPosition: SnackPosition.BOTTOM,
backgroundColor: backgroundColor,
colorText: Colors.white);
}
// 登录接口
Future<bool> loginService(String username, String password) async {
try {
final response = await apiService.dio.post(
'user/login',
data: {
'username': username,
'password': password,
},
);
// success
if (response.statusCode == 200) {
var data = response.data;
String? dataStatusCode = data['statusCode'];
// 600错误码表示用户名或密码错误
if (dataStatusCode == '600') {
String message = data['message'];
apiService.showFeedback('登录', 'Login failed: $message', Colors.red);
return false;
} else if (dataStatusCode == '200') {
String? token = data['data']['token'];
if (token != null) {
isAuthenticated = true.obs;
// 保存token
storageService.saveToken(token);
// 将返回json数据转换为User对象,并存储
user.value = User.fromJson(data['data']['user']);
storageService.saveUser(user.value!.toJson());
apiService.showFeedback('登录成功', 'Login successful', Colors.green);
return true;
}
}
}
} on dio.DioError catch (e) {
// DioError中会包含后端返回的实际statusCode和数据
if (e.response != null) {
print('Error statusCode: ${e.response!.statusCode}');
print('Error response data: ${e.response!.data}');
// 其他错误
apiService.showFeedback('登录', 'Login failed: Unknown error', Colors.red);
} else {
// Error without response data
apiService.showFeedback('登录', 'Login failed: Error occurred', Colors.red);
}
}
return false;
}