如何确保方法等待http响应而不是在Dart中返回null?

时间:2014-09-20 12:50:01

标签: facebook dart

我正在尝试在Dart中编写一个小命令行库来使用Facebook API。我有一个类'fbuser',它获取auth-token和user-id作为属性,并且有一个方法'groupIds',它应该返回一个List,其中包含来自用户的所有组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。

(今年夏天我开始编程。感谢您的帮助。)

1 个答案:

答案 0 :(得分:7)

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
}