Last active
September 15, 2020 08:55
-
-
Save bharathraj-e/a4c3eb52684e5034ad237bbe4e3512be to your computer and use it in GitHub Desktop.
Flutter http request simplified
This file contains hidden or 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
import 'dart:convert'; | |
import 'package:http/http.dart' as http; | |
const String _host = "https://<....>"; | |
class MyRequest { | |
final String url; | |
final Map<String, String> headers = {'Authorization': 'Bearer token'}; | |
Map<String, dynamic> _response; | |
dynamic get data => _response.containsKey('data') ? _response['data'] : null; | |
MyRequest(String path) : this.url = "$_host/$path"; | |
Future<Map<String, dynamic>> gets(String path,{Map<String, String> query}) async { | |
String link = "$url"; | |
if (query != null) { | |
final List<String> params = []; | |
query.forEach((k, v) => params.add('$k=$v')); | |
link += "?${params.join('&')}"; | |
} | |
try { | |
final http.Response response = await http.get(link, headers: headers); | |
return _parseResponse(response.body); | |
} catch (e) { | |
print(e); | |
return null; | |
} | |
} | |
Future<Map<String, dynamic>> post(String path, Map<String, String> body) async { | |
try { | |
final http.Response response = | |
await http.post(url, headers: headers, body: body); | |
return _parseResponse(response.body); | |
} catch (e) { | |
print(e); | |
return null; | |
} | |
} | |
Map<String, dynamic> _parseResponse(String body) { | |
print(body); | |
try { | |
Map<String, dynamic> res = json.decode(body); | |
if (!res.containsKey('ok')) return null; | |
if (res['ok'] != true) return null; | |
_response = res; | |
return res; | |
} catch (e) { | |
print(e); | |
return null; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment