Skip to content

Instantly share code, notes, and snippets.

@hayabusabusa
Created January 20, 2021 06:40
Show Gist options
  • Save hayabusabusa/9551dfe61c52f9a6e431dcf9c38840db to your computer and use it in GitHub Desktop.
Save hayabusabusa/9551dfe61c52f9a6e431dcf9c38840db to your computer and use it in GitHub Desktop.
Flutter API client class with http package
import 'package:http/http.dart' as http;
import './api_request.dart';
import './api_error.dart';
import './api_method.dart';
abstract class APIClientInterface {
Future<T> call<T>(APIRequest<T> request);
}
class APIClient implements APIClientInterface {
APIClient._();
static APIClient _instance;
static APIClient get instance {
if (_instance == null)
_instance = APIClient._();
return _instance;
}
final _client = http.Client();
Future<T> call<T>(APIRequest<T> request) async {
final url = request.baseURL + request.path;
final headers = request.headers;
http.Response response;
switch (request.method) {
case APIMethod.GET:
response = await _client.get(url, headers: headers);
break;
case APIMethod.POST:
response = await _client.post(url, headers: headers);
break;
}
if (response.statusCode != 200) {
throw APIError(statusCode: response.statusCode, message: response.body);
}
return request.decode(response);
}
}
import 'package:flutter/foundation.dart';
class APIError extends Error {
APIError({
@required this.statusCode,
@required this.message,
});
final int statusCode;
final String message;
@override
String toString() => '${statusCode}: ${message}';
}
enum APIMethod {
GET,
POST,
}
import 'package:http/http.dart' as http;
import './api_method.dart';
abstract class APIRequest<T> {
String get baseURL => 'http://endpoint';
String get path;
APIMethod get method => APIMethod.GET;
Map<String, String> get headers => {
'Content-Type': 'application/json',
};
T decode(http.Response response);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment