1、baseProvider.dart 文件,里面实现请求的拦截和响应的处理
c
import 'dart:convert';
import 'package:company_manage_flutter/config/setting.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get_connect/connect.dart';
class BaseProvider extends GetConnect {
@override
void onInit() {
super.onInit();
print('拦截器初始化');
httpClient.baseUrl = ProjectConfig.baseUrl;
// 请求拦截
httpClient.addRequestModifier<void>((request) {
print('====================请求拦截====================');
// 获取 POST 请求的参数
var uri = Uri.parse(request.url.toString());
var extra = uri.queryParameters;
if (extra["isShowLoading"] == "1") {
EasyLoading.show(status: '请求中');
}
// request.headers['Authorization'] = '12345678';
return request;
});
// 响应拦截
httpClient.addResponseModifier((request, response) {
print('====================响应拦截====================');
print(response.body);
EasyLoading.dismiss();
// 将 body 转换为 Map 类型
return response;
});
}
}
2、封装接口文件userAPI.dart
c
import 'dart:convert';
import 'package:company_manage_flutter/api/formateResponse.dart';
import 'package:company_manage_flutter/utils/baseProvider.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get_connect/connect.dart';
class UserApi extends BaseProvider {
UserApi() {
onInit();
}
//登录
Future<List<dynamic>> loginAPI({Map<String, dynamic>? params}) async {
var response = await post('/app/login', params, query: requestExtraParams);
List<dynamic> result = formateResponse(response);
return result;
}
}
3、封装响应数据和请求参数
c
import 'dart:convert';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get_storage/get_storage.dart';
List<dynamic> formateResponse(response) {
Map<String, dynamic> result = jsonDecode(response.body.toString());
print('返回结果${result}');
if (response.statusCode == 200) {
if (result["code"] != 200) {
EasyLoading.showError(result["msg"]);
return [result["msg"], null];
} else {
return [null, result];
}
} else {
EasyLoading.showError('请求错误,请稍后再试!');
return ["请求错误,请稍后再试", null];
}
}
Map<String, dynamic> requestExtraParams = {"isShowLoading": "1"};
Map<String, dynamic> getTokenParams(Map<String, dynamic>? params) {
GetStorage box = GetStorage();
Map<String, dynamic> loginUser = box.read('loginUser');
Map<String, dynamic> tokenParams = {
"token": loginUser["token"],
"uid": loginUser["uid"],
};
// 合并 params 和 tokenParams
Map<String, dynamic> mergedParams = {
...params ?? {},
...tokenParams,
};
return mergedParams;
}
4、具体使用
c
params = {"login": "admin", "password": "admin"};
List<dynamic> result = await userApi.loginAPI(params: params);
if (result[0] != null) return;
Map<String, dynamic> data = result[1];
//1、把数据存储到story 和 状态中
GetStorage box = GetStorage();
box.write('loginUser', data);
loginController.setLoginUser(data);
Get.to(IndexPage());