How can I make sure the method is waiting for an HTTP response instead of returning null in the Dart?

I am trying to write a small command line library in Dart to work with the Facebook API. I have a fbuser class that receives the auth-token attribute and user-id as properties and has a "groupIds" method, which should return a List with all group identifiers from the user.

When I call the method, it returns null, but after an HTTP response, two possible results are called. What have I done 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
}

Currently output:

Observatory listening on http://127.0.0.1:56918
null
response received
174 Gruppen gefunden

The method launches an HTTP request, but immediately returns null.

(I started programming this summer. Thanks for your help.)

+4
source share
1 answer
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
}
+7
source

All Articles