Danny
Danny

Reputation: 506

returns Instance of '_Future<List<MODELNAME>>' instead of json

i have an API that returns a list of places as JSON, and it works well on postman, but i cant get it to return it on Flutter.

here is the function that returns all the places

Future<List<PlacesModel>> getAllPlaces() async {
  final Storage _localStorage = window.localStorage;
  List<PlacesModel> allPlaces = [];

  Map<String, String> headers = {
    'Content-type': 'application/json',
    'Authorization': 'Bearer ${_localStorage['token']}'
  };
  final allPlacesURl = Uri.parse("http://localhost:3000/common/getPlaces/0");

  var response = await http.get(allPlacesURl, headers: headers);
  if(response.statusCode == 200)
    {
      final decodee = "[" + response.body +"]";
      List body = json.decode(decodee);
      allPlaces = body.map((e) => PlacesModel.fromJson(e)).toList();
      return allPlaces;
    }
}

but it just returns Instance of '_Future<List<PlacesModel>>' instead of the actual json list.

Upvotes: 0

Views: 247

Answers (3)

ritik kumar srivastava
ritik kumar srivastava

Reputation: 550

If you really want to pass the json list instead of a list of the placemodel defined by you then go for the following code snippet and the function call should be like:

//function call
var result = await getAllPlaces();// has the json map required and this can further be processed as a json.


//function definition
Future getAllPlaces() async {
  final Storage _localStorage = window.localStorage;

  Map<String, String> headers = {
    'Content-type': 'application/json',
    'Authorization': 'Bearer ${_localStorage['token']}'
  };
  final allPlacesURl = Uri.parse("http://localhost:3000/common/getPlaces/0");

  var response = await http.get(allPlacesURl, headers: headers);
  if(response.statusCode == 200)
    {
      return response.body;
    }
  else{
      return null;
    }
}

Upvotes: 1

Anas Nadeem
Anas Nadeem

Reputation: 887

REPLACE THIS:

if(response.statusCode == 200)
    {
      final decodee = "[" + response.body +"]";
      List body = json.decode(decodee);
      allPlaces = body.map((e) => PlacesModel.fromJson(e)).toList();
      return allPlaces;
    }

WITH:

    if(response.statusCode == 200)
    {
      return response.body;
    }

Upvotes: 0

Huthaifa Muayyad
Huthaifa Muayyad

Reputation: 12353

Where you are calling getAllPlaces use await before it:

List<PlacesModel> someList = await getAllPlaces();

Upvotes: 0

Related Questions