Problem with the return value from a Future async function

I've created a function that gets a json from an api. The problem is that the function is not returning a value. It returns 'Instance of Future...'

I've tried different ways of solving it. If I print the value that is supposed to return (print(extractdata[1])) It actually returns what it's supposed to:

{
   id: 2
   name: Sala 2,
   beds: [
       {
           id: 3,
           name: Cama 3,
           paciente: null
       },
       {
           id: 4,
           name: Cama 4,
           paciente: null
       }
   ]
}

Future <List> getRoom() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    var _token = prefs.getString('token');
    final response = await http.get('http://10.0.2.2:8000/api/room/',
    headers: {'Authorization':'JWT $_token'}
    ).then((res){
      var extractdata = JSON.jsonDecode(res.body);
      return extractdata;
    });
  }

I expect the output to be the list of all rooms but instead it returns 'Instance of Future...'. If I try to get the length it works if I print it inside the function but if I call the function and then ask for length it does not work.

1 answer

  • answered 2019-05-21 20:21 siega

    As you are using async/await, you do not need to use then.

    Future <List> getRoom() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        var _token = prefs.getString('token');
    
        final response = await http.get('http://10.0.2.2:8000/api/room/',
            headers: {'Authorization':'JWT $_token'}
        );
    
        var extractdata = JSON.jsonDecode(response.body);
        return extractdata;
    }