0

当我ListView从从服务器返回的数据女巫实现分页时,我可以简单地测试这种分页能力并且工作正常,例如通过这段代码我可以通过简单数据制作列表列:

list.add(
    PostItem((b) =>b
        ..title = 'lorem ipsum'
        ..colorInt = _randomGenerator.nextInt(0xFFFFFFFF)),
    );

return BuiltList.of(list);

现在我正在尝试从服务器获取数据并从中获取这些数据:

List<PostItem> list = [
  PostItem((b)=>b..title = 'lorem ipsum'),
  PostItem((b)=>b..title = 'lorem ipsum')
];

我得到错误:

List<PostItem> list=[];

final response = await http.get(Constants.getPosts, headers: {"Accept": "application/json"});

final responseString = json.decode(response.body) as List;

List<ContentsModel> responses = responseString.map((j) => 
    ContentsModel.fromJson(j)).toList();

responses.map((post)=>
    list.add(PostItem((b) => b..title = post.title),));

return BuiltList.of(list);

在这条线的大小list为零:

response.map((post)=>list.add(PostItem((b) => b..title = post.title),));

我的ContentsModel课程内容是:

part 'contents_model.g.dart';

@JsonSerializable(nullable: false)
class ContentsModel{
  int id;
  String title;
  String description;

  ContentsModel(this.id, this.postId, this.title, this.description, this.type, this.featuredImages, this.slug, this.lang, this.visit, this.click, this.state, this.createdAt, this.updatedAt, this.categories);

  factory ContentsModel.fromJson(Map<String,dynamic> json)=>_$ContentsModelFromJson(json);
  Map<String,dynamic> toJson()=>_$ContentsModelToJson(this);
}
4

2 回答 2

1

在添加一些内容之前,您需要初始化您的列表:

List<PostItem> list = [];
于 2019-06-11T11:07:36.977 回答
0

改变

responses.map((post)=>
    list.add(PostItem((b) => b..title = post.title),));

responses.forEach((post)=>list.add(PostItem((b) =>b..title = post.title)));

解决了我的问题

于 2019-06-11T11:46:40.623 回答