遍历显示自定义的widget

需求

  • 列表展示: 列表项都是同一格式,列表项数据从List里取

解决方案

  • 使用map

map源码

  Iterable<T> map<T>(T f(E e)) => MappedIterable<E, T>(this, f);
  • 调用map 返回的数据类型为Iterable
  • 注意1: 需要将Iterable转换为List,使用toList,此时返回的数据类型为List
  • 注意2: 由于返回的是List,所以必须要一个可接收数组的属性,比如: children、items

代码

static List<Job> getRecommendJobList() {
    List<Job> items = [];
    for (int i = 0; i < 5; i++) {
      Job obj = new Job();
      obj.jobsName = "货运代理业务代表";
      obj.companyName = "青岛中创远铁物流有限公司";
      obj.districtCn = "山东/青岛";
      obj.wageCn = "4.0K-8.0K/月";
      obj.refreshTimeCn = "4小时前";
      items.add(obj);
    }
    return items;
  }
List<Job> recommendJobList = getRecommendJobList();
...
...
...
Column( children: recommendJobList.map<Widget>((e) => _recommendJob(e)).toList(), )
...
...
...
Widget _recommendJob(Job object) {
    return Container(
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: <Widget>[
          Text(object.jobsName, style: TextStyle(fontSize: 20),),
          Text("${object.companyName} | ${object.districtCn}"),
        ],
      ),
    );
  }
原文地址:https://www.cnblogs.com/shellon/p/13529647.html