Created
March 21, 2022 06:45
-
-
Save dev4jam/1103416930f83caf7528279aa43731e5 to your computer and use it in GitHub Desktop.
Network Service Prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class NetworkService { | |
NetworkService({ | |
required this.baseUrl, // Base service url | |
dioClient, // Prepared Dio instance could be injected | |
httpHeaders, // Global headers could be provided as well | |
}) : this._dio = dioClient, | |
this._headers = httpHeaders ?? {}; | |
Dio? _dio; | |
final String baseUrl; | |
Map<String, String> _headers; | |
Future<Dio> _getDefaultDioClient() async { | |
// Global http header | |
_headers['content-type'] = 'application/json; charset=utf-8'; | |
final dio = Dio.Dio() | |
..options.baseUrl = baseUrl | |
..options.headers = _headers | |
..options.connectTimeout = 5000 // 5 seconds | |
..options.receiveTimeout = 3000; // 3 seconds | |
return dio; | |
} | |
// Generic type and parser are used to properly deserialise JSON | |
Future<NetworkResponse<Model>> execute<Model>( | |
NetworkRequest request, | |
Model Function(Map<String, dynamic>) parser, { | |
ProgressCallback? onSendProgress = null, | |
ProgressCallback? onReceiveProgress = null, | |
}) async { | |
if (_dio == null) { | |
_dio = await _getDefaultDioClient(); | |
} | |
// 1. Prepare the request | |
// 2. Execute it | |
// 3. Return parsed result or error | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment