Search code examples
flutterflutter-webdio

Dio error when converting flutter app to flutter web


So I had developed an application on flutter which uses Dio to make HTTP requests.

I tried to use this application as a flutter web application but do seems to give me error.

Here is my code for the HTTP service:

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;
  }
}

What I think is the cause of the error is:

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

As when I run this on chrome it gives an error Expected a value of type 'DefaultHttpClientAdapter', but got one of type 'BrowserHttpClientAdapter'

How do I solve this issue and get my app running on a chrome browser?


Solution

  • For debug purpose you can remove that code for web or you can give following condition:

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