Monday, April 4, 2022

Flutter Tutorial: Create Network Service Library for Better API Call in Flutter

 In this tutorial we will create a library function in flutter to provide easy API connection. Our function will use a better known flutter packages like HTTP and DIO. 

Our goals is create a network services that:

✅ Has No duplicate code 

✅ Has Not blocking main thread and dropping FPS

 ✅ Has No error-proof codebase 

✅ Has Minimised time on adding new services and API calls 

✅ Has Structured and strongly-typed error handling

Example code:

class NetworkService {
  NetworkService({
    required this.baseUrl,
    dioClient,
    httpHeaders,
  })  : this._dio = dioClient,
        this._headers = httpHeaders ?? {};
  Dio? _dio;
  final String baseUrl;
  Map _headers;
  Future _getDefaultDioClient() async {
    _headers['content-type'] = 'application/json; charset=utf-8';
    final dio = Dio()
      ..options.baseUrl = baseUrl
      ..options.headers = _headers
      ..options.connectTimeout = 5000 // 5 seconds
      ..options.receiveTimeout = 3000; // 3 seconds
      
    }
    return dio;
  }
  void addBasicAuth(String accessToken) {
    _headers['Authorization'] = 'Bearer $accessToken';
  }
  Future> execute(
    NetworkRequest request,
    Model Function(Map) parser, {
    ProgressCallback? onSendProgress = null,
    ProgressCallback? onReceiveProgress = null,
  }) async {
    if (_dio == null) {
      _dio = await _getDefaultDioClient();
    }
    final req = _PreparedNetworkRequest(
      request,
      parser,
      _dio!,
      {..._headers, ...(request.headers ?? {})},
      onSendProgress,
      onReceiveProgress,
    );
    final result = await compute(
      executeRequest,
      req,
    );
    return result;
  }
}

0 comments:

Post a Comment