首页 > 解决方案 > Flutter ListView 在 itemCount 参数中获取一些项目

问题描述

正如我们所知,我们itemCountListView小部件中有 100 多个项目,我只想从中获取 10 个项目,例如:

itemCount: _dashboardViewModel.media.where((element) => element.type=='images').length,

length是 100,我怎么能只取itamCount参数中的 10 项?

child: Container(
  padding: const EdgeInsets.only(left: 10.0, right: 10.0),
  child: ListView.separated(
    scrollDirection: Axis.horizontal,
    itemBuilder: (context, index) {
      return ...;
    },
    itemCount: _dashboardViewModel.media.where((element) => element.type=='images').length,
    separatorBuilder: (context, index) {
      return Center(
        child: Container(
          width: 6.0,
          height: 6.0,
          margin: const EdgeInsets.only(top: 20, right: 5.0, left: 5.0, bottom: 15.0),
          decoration: BoxDecoration(
            color: Colors.black.withOpacity(0.1),
            shape: BoxShape.circle,
          ),
        ),
      );
    },
  ),
),

标签: flutterdart

解决方案


我建议你使用take(),它可以帮助你在这种情况下获得你想要的前 n 个数字,first 10 numbers

toList()这种方法不是强制性的,所以从代码中删除它仍然会给出长度。

指针:如果您List出于某种原因专门需要一个对象类型,那么您可能想要使用toList(). 但在这种情况下不是。

itemCount: _dashboardViewModel.media.where((element) => element.type=='images').take(10).length

推荐阅读