heyr
heyr

Reputation: 5794

Push objects into array in Dart

  List returnMovies = [];

Future<List> _getData() async {

    final response = await http.get("https:../getTodayMovies",
        headers: {HttpHeaders.AUTHORIZATION: Acess_Token.access_token});


    if (response.body != null) {
    returnMovies = json.decode(response.body);
      .....

      setState(() {});
    } else {
       final responseUpcoming = await http.get("/upcoming",
        headers: {HttpHeaders.AUTHORIZATION: Acess_Token.access_token});
        returnMovies = json.decode(responseUpcoming.body);


    }

The response.body looks like:

[{"id":394470548,"host_group_name":"heyab redda","movie_image":"..png","type":"horror","code":"X123","name":"Lovely","start_time":1554364800,"end_time":1554393600,"}]

The responseUpcoming.body looks like:

 {"id":394470545,"host_group_name":"foo redda","movie_image":".png","type":"horror","code":"X123","name":"Lovely","start_time":1554364800,"end_time":1554393600,"}, {"id":394470548,"host_group_name":"foo1 redda","movie_image":"..png","type":"comic","code":"X125","name":"Lovely1","start_time":1554364800,"end_time":1554393600,"}

The error I get is: String, dynamic is not a subtype of type List<dynamic>.

In the first API call that I am doing I normally get in return an array of objects, however, when this is empty, the second API call returns a list of objects that I want to push into the array called returnMovies, how can I achieve this?? Is there any way to .push these objects in the array?? So then I want to use this array to build dynamically a Listview.builder. Also is it correct the way I am declaring it? I am quite new on Dart. Thank you

Upvotes: 17

Views: 41091

Answers (3)

dmarquina
dmarquina

Reputation: 4086

When you do this json.decode(response.body) you are getting a List of Map you should use List<dynamic> movieListData and get the items like this:

    movieListData = json.decode(response.body);
    returnMovies = movieListData.map((dynamic movieData) {
          String id = movieData['_id'];
          String host_group_name = movieData['host_group_name'];
          String duration = movieData['duration'];
          return new Movie(id,title, duration);
        }).toList();

Upvotes: 2

Mohamed hassan kadri
Mohamed hassan kadri

Reputation: 1069

I will suggest to use

returnMovies.addAll({your object here})

Upvotes: 5

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 658263

Sounds like you are looking for addAll

returnMovies.addAll(json.decode(returnUpcoming.body))

Upvotes: 13

Related Questions