I am trying to write a little command line library in Dart to work with the Facebook API. I have a class 'fbuser' which gets the auth-token and user-id as properties and has a method 'groupIds' which should return a List with all IDs of groups from the user.
When I call the method it returns null altough the two possbile returns are called after the http response. What did I do wrong?
Here is my code:
import 'dart:convert'; //used to convert json
import 'package:http/http.dart' as http; //for the http requests
//config
final fbBaseUri = "https://graph.facebook.com/v2.1";
final fbAppID = "XXX";
final fbAppSecret = "XXY";
class fbuser {
int fbid;
String accessToken;
fbuser(this.fbid, this.accessToken); //constructor for the object
groupIds(){ //method to get a list of group IDs
var url = "$fbBaseUri/me/groups?access_token=$accessToken"; //URL for the API request
http.get(url).then((response) {
//once the response is here either process it or return an error
print ('response received');
if (response.statusCode == 200) {
var json = JSON.decode(response.body);
List groups=[];
for (int i = 0; i<json['data'].length; i++) {
groups.add(json['data'][i]['id']);
}
print(groups.length.toString()+ " Gruppen gefunden");
return groups; //return the list of IDs
} else {
print("Response status: ${response.statusCode}");
return (['error']); //return a list with an error element
}
});
}
}
void main() {
var usr = new fbuser(123, 'XYY'); //construct user
print(usr.groupIds()); //call method to get the IDs
}
At the moment the output is:
Observatory listening on http://127.0.0.1:56918
null
response received
174 Gruppen gefunden
The method runs the http request but it returns null immediately.
(I started programming this summer. Thanks for your help.)
return http.get(url) // add return
void main() {
var usr = new fbuser(123, 'XYY'); //construct user
usr.groupIds().then((x) => print(x)); //call method to get the IDs
// or
usr.groupIds().then(print); //call method to get the IDs
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With