使用map代替for语句使类模型中的列表返回零

时间:2019-06-11 11:04:01

标签: flutter dart built-value

当我实现从服务器返回的数据巫婆的分页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的行大小为零:

  

responses.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);
}

2 个答案:

答案 0 :(得分:1)

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

List<PostItem> list = [];

答案 1 :(得分:0)

更改

with open("path/to/logfile.log", "r") as f:
    lines = f.readlines()
    for error in errors:
        for line in lines[-5:]:
            if error in line:
                return True
    return False

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

解决了我的问题