将 flutter app 转换为 flutter web 时出现 Dio 错误

Dio error when converting flutter app to flutter web

所以我在 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 浏览器上获取我的应用程序 运行ning?

出于调试目的,您可以为网络删除该代码,或者您可以提供以下条件:

if(!kIsWeb){
    (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
        (HttpClient client) {
      client.badCertificateCallback =
          (X509Certificate cert, String host, int port) => true;
      return client;
    };
}