【问题标题】:Dio error when converting flutter app to flutter web将 Flutter 应用程序转换为 Flutter Web 时出现 Dio 错误
【发布时间】:2021-06-28 01:48:06
【问题描述】:

所以我在 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 浏览器上运行?

【问题讨论】:

  • 您应该尝试使用“flutter run -d chrome --web-renderer html”运行
  • @NileshSenta 仍然遇到同样的错误。
  • @FemnDharamshi 你得到答案了吗?
  • 是的,我做到了。感谢您的跟进@PratikButani

标签: flutter flutter-web dio


【解决方案1】:

出于调试目的,您可以删除网页代码,或者您可以给出以下条件:

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

【讨论】:

    猜你喜欢
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2021-03-04
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多