4
我想在Dart中編寫一個小命令行庫來與Facebook API一起工作。我有一個類'fbuser',它將auth-token和user-id作爲屬性獲取,並有一個方法'groupIds',它應該返回一個List,其中包含來自用戶的所有組的ID。如何確保方法等待http響應而不是在Dart中返回null?
當我調用該方法時,它將返回null,儘管在http響應之後調用了兩個possbile返回值。我做錯了什麼?
這裏是我的代碼:
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請求,但空立即返回。
(我開始這個夏天的編程。感謝您的幫助。)
謝謝!完美的作品。 – Luca 2014-09-20 13:13:07