在Dart中将对象推入数组

时间:2019-02-18 15:20:04

标签: dart flutter

  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);


    }

response.body类似于:

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

responseUpcoming.body如下:

 {"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,"}

我得到的错误是:字符串,动态不是List<dynamic>类型的子类型。

在我执行的第一个API调用中,我通常会返回一个对象数组,但是,当该对象为空时,第二个API调用将返回要推送到名为returnMovies的数组中的对象列表。我能做到这一点吗?有什么方法可以将这些对象推送到数组中?因此,我想使用此数组动态构建Listview.builder。 我声明的方式也正确吗?我对Dart很陌生。谢谢

3 个答案:

答案 0 :(得分:1)

我建议使用

returnMovies.addAll({your object here})

答案 1 :(得分:0)

听起来像您在寻找addAll

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

答案 2 :(得分:0)

进行此操作json.decode(response.body)时,您会得到List中的Map,应使用List<dynamic> movieListData并获得以下项目:

    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();