I'm new Dart and have an iOS background so I might be using the language incorrectly which is leading to my code not working as expected but I also cannot find a solution online and thought I would ask it here incase someone else has experienced it and fixed it.
So what I'm trying to accomplish is have a model factory create a datasource in which you pass the request type (GET or POST), pass in an endpoint, and some params. Then it will return you back a future in which you listen for a then()
call, this is called when the network request is successful/fails. The code I currently have works up until the point when I call completion.complete(responseObject);...nothing happens after that.
Code for the few functions that are involved:
Inside the Model Factory:
BaseDataSource bds = new BaseDataSource();
Map params = {"api_key": "random","session_id": "random", "account_id": "random"};
Future<Map> request = bds.makeRequest(NetworkingRequestType.GET, params, "music/songs");
request.then((Map responseObject) {
});
Inside the Datasource:
enum NetworkingRequestType {
GET, POST
}
class BaseDataSource {
static final String baseServerURL = config[appRunMode]["baseServerURL"];
Future<Map> makeRequest(NetworkingRequestType type, Map params, String endpoint) {
Future<Map> completion;
switch (type) {
case NetworkingRequestType.GET:
completion = _makeGetRequest(endpoint, params);
break;
case NetworkingRequestType.POST:
break;
}
return completion;
}
Future<Map> _makeGetRequest(String endpoint, Map params) {
final uri = new Uri(path: "${baseServerURL}${endpoint}",
queryParameters: params);
return HttpRequest.getString("${uri}").then(JSON.decode);
}
}
I can't spot anything wrong with this code, except that it does not propagate errors. It should work. If completion.complete
is invoked then completion.future
must complete, check that completion.complete
is indeed invoked (e.g. check if there were any network errors on the console, check Network tab in DevTools to see request/response).
In general though I'd recommend avoiding explicit usage of completers. Just use the future returned by then
instead of completer.future
:
Future<Map> makeRequest(NetworkingRequestType type, Map params, String endpoint) {
switch (type) {
case NetworkingRequestType.GET:
return _makeGetRequest(endpoint, params);
case NetworkingRequestType.POST:
break;
}
}
Future<Map> _makeGetRequest(String endpoint, Map params) {
final uri = new Uri(path: "${baseServerURL}${endpoint}",
queryParameters: params);
return HttpRequest.getString("${uri}").then(JSON.decode);
}