我正在尝试使用Dart编写一个小型的命令行库,以便与Facebook API一起使用。我有一个名为'fbuser'的类,它获取身份验证令牌和用户ID作为属性,并具有一个名为'groupIds'的方法,该方法应返回用户所有群组的ID列表。
当我调用该方法时,它返回null,尽管在http响应后已经调用了两个可能的返回值。我做错了什么?
以下是我的代码:
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
}
目前的输出结果是:
Observatory listening on http://127.0.0.1:56918
null
response received
174 Gruppen gefunden
该方法运行了http请求,但立即返回null。
(我今年夏天开始学习编程,感谢您的帮助。)