You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.5 KiB

2 years ago
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:platform/platform.dart';
2 years ago
2 years ago
import '../../constants/api.dart';
import '../../utils/toast/cloud_toast.dart';
2 years ago
import '../../utils/inner_model/base_list_model.dart';
2 years ago
import 'base_model.dart';
import 'net_interceptor.dart';
final ApiClient apiClient = ApiClient();
class ApiClient {
late Dio _dio;
Dio get dio => _dio;
ApiClient() {
var headers = <String, dynamic>{};
if (kIsWeb) {
headers = {'device-type': 'web'};
} else {
headers = {
'device-type': const LocalPlatform().operatingSystem.toLowerCase()
};
}
_dio = Dio()
..options.baseUrl = API.baseURL
..options.headers = headers
..interceptors.add(NetworkInterceptor());
}
///设置token
Dio setToken(String token) {
return _dio..options.headers[API.tokenKey] = token;
}
///清除token
Dio clearToken() {
return _dio
..options.headers.removeWhere((key, value) => key == API.tokenKey);
}
///发送请求
Future<BaseModel> request(
String path, {
dynamic data,
bool showMessage = false,
}) async {
try {
var response = await _dio.post(path, data: data);
var baseModel = BaseModel.fromJson(response.data);
if (showMessage) CloudToast.show(baseModel.msg);
return baseModel;
} catch (e) {
if (e is DioError) {
return BaseModel.dioErr(e);
}
}
return BaseModel.unknown();
}
///请求列表
Future<BaseListModel> requestList(
String path, {
dynamic data,
bool showMessage = false,
}) async {
var response = await _dio.post(path, data: data);
var baseModel = BaseListModel.fromJson(response.data);
if (showMessage) CloudToast.show(baseModel.msg);
return baseModel;
}
2 years ago
2 years ago
// ///上传图片
// Future<String> uploadImage(File file) async {
// var response = await _dio.post(
// API.file.uploadImage,
// data: FormData.fromMap(
// {'image': await MultipartFile.fromFile(file.path)},
// ),
// );
// var model = BaseModel.fromJson(response.data);
// return model.data['path'];
// }
// Future<List<String>> uploadFiles(
// List<File> files,
// ) async {
// List<String> urls = [];
// if (files.isEmpty) {
// return [];
// } else {
// for (var item in files) {
// String path = await uploadImage(item);
// if (path.isNotEmpty) {
// urls.add(path);
// }
// }
// }
// return urls;
// }
}