所以我在flutter上开发了一个应用程序,它使用Dio来发出HTTP请求。
我尝试将此应用程序用作 flutter web 应用程序,但似乎给了我错误。
这是我的 HTTP 服务代码:
import 'dart:io';
import 'package:dio/adapter.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:jura_saas/core/service_locator.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';
import 'package:jura_saas/core/constants/api_routes.dart';
import 'package:jura_saas/core/services/file_helper.dart';
import 'package:jura_saas/core/services/preference_service.dart';
class HttpService {
var _dio;
final PreferenceService _preferenceService = locator<PreferenceService>();
HttpService() {
_dio = Dio();
_dio.options.baseUrl = ApiRoutes.baseURL;
_dio.interceptors.add(
InterceptorsWrapper(
onRequest: (RequestOptions options,
RequestInterceptorHandler requestInterceptorHandler) {
String authToken = _preferenceService.getAuthToken();
if (authToken.isNotEmpty) {
options.headers["Authorization"] = "Bearer " + authToken;
return options;
}
},
),
);
_dio.interceptors.add(
PrettyDioLogger(
requestHeader: true,
requestBody: true,
responseBody: true,
responseHeader: false,
error: true,
compact: true,
maxWidth: 90),
);
(_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) {
client.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
return client;
};
}
final _fileHelper = locator<FileHelper>();
Future<Response> getHttp(String route,
{Map<String, dynamic> queryParams}) async {
Response response;
try {
final fullRoute = '$route';
response = await _dio.get(
fullRoute,
queryParameters: queryParams,
options: Options(
contentType: 'application/json',
),
);
} on DioError catch (e) {
// _log.e('HttpService: Failed to GET ${e.message}');
// print("Reached!");
// throw Exception(e.message);
//TODO: Add the next statement to all the other responses.
response = e.response;
//TODO: I have removed the throw exception, so that even 401 works!
}
// _log.i(response.data);
// For this specific API its decodes json for us
return response;
}
Future<Response> deleteHttp(String route,
{Map<String, dynamic> queryParams}) async {
Response response;
try {
final fullRoute = '$route';
response = await _dio.delete(
fullRoute,
queryParameters: queryParams,
options: Options(
contentType: 'application/json',
),
);
} on DioError catch (e) {
// _log.e('HttpService: Failed to GET ${e.message}');
throw Exception(e.message);
}
// _log.i(response.data);
// For this specific API its decodes json for us
return response;
}
Future<Response> postHttp(String route, dynamic body) async {
Response response;
try {
final fullRoute = '$route';
response = await _dio.post(
fullRoute,
data: body,
options: Options(
contentType: 'application/json',
),
);
} on DioError catch (e) {
// _log.e('HttpService: Failed to GET ${e.message}');
// print("Reached!");
// throw Exception(e.message);
//TODO: Add the next statement to all the other responses.
response = e.response;
// I have removed the throw exception, so that even 401 works!
}
// _log.i(response.data);
// For this specific API its decodes json for us
return response;
}
Future<Response> delHttp(String route, dynamic body) async {
Response response;
try {
final fullRoute = '$route';
response = await _dio.delete(
fullRoute,
data: body,
options: Options(
contentType: 'application/json',
),
);
} on DioError catch (e) {
return e.response;
// throw Exception(e.message);
}
// For this specific API its decodes json for us
return response;
}
Future<Response> postHttpForm(
String route,
Map<String, dynamic> body,
Map<String, dynamic> files,
) async {
var index = 0;
final formData = FormData.fromMap(body);
files?.forEach((keys, value) async {
if (value != null) {
final mFile = await _fileHelper.convertFileToMultipartFile(value);
formData.files.add(MapEntry(keys, mFile));
} else {
formData.files.add(MapEntry(keys, null));
}
index++;
});
final data = await postHttp(route, formData);
return data;
}
Future<Response> postHttpFormExperience(
String route,
Map<String, dynamic> body,
List<File> files,
) async {
var index = 0;
final formData = FormData.fromMap(body);
files?.forEach((value) async {
if (value != null) {
final mFile = await _fileHelper.convertFileToMultipartFile(value);
formData.files.add(MapEntry("pic", mFile));
} else {
formData.files.add(MapEntry("pic", null));
}
index++;
});
final data = await postHttp(route, formData);
return data;
}
Future<Response> delHttpForm(
String route,
Map<String, dynamic> body,
) async {
final formData = FormData.fromMap(body);
final data = await delHttp(route, formData);
return data;
}
}
我认为错误的原因是:
(_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) {
client.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
return client;
};
当我在 chrome 上运行它时,它给出了一个错误
Expected a value of type 'DefaultHttpClientAdapter', but got one of type 'BrowserHttpClientAdapter'
如何解决此问题并使我的应用程序在 Chrome 浏览器上运行?
出于调试目的,您可以删除该网络代码,或者您可以给出以下条件:
if(!kIsWeb){
(_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
(HttpClient client) {
client.badCertificateCallback =
(X509Certificate cert, String host, int port) => true;
return client;
};
}
我为此使用了另一种方法。最初,我尝试修改 Flutter 文件,但这种方法遇到了问题。对我有用的解决方案是仅运行此命令:
flutter run -d chrome --web-browser-flag "--disable-web-security"
就是这样!这应该可以解决问题。