[译]Flutter分组列表组件grouped_list

1,813 阅读2分钟

原文:grouped_list | Flutter Package (flutter-io.cn)

译时版本:5.1.2

Flutter分组列表组件grouped_list

pub package package publisher build

一个 Flutter ListView ,列表中的组件可分组为多个部分。 

image.pngimage.png

特性

  • 支持空安全!
  • 便于创建聊天窗口。
  • 列表项目可分隔为不同的组。
  • 可分别设置每个组的头部。
  • 几乎 ListView.builder 的所有属性项目都是可用的。

开始

添加库到 pubspec.yaml 中:

 grouped_list: ^5.1.2

在 Dart 文件中,导入库:

import 'package:grouped_list/grouped_list.dart';

创建 GroupedListView 组件代替 ListView :

  GroupedListView<dynamic, String>(
    elements: _elements,
    groupBy: (element) => element['group'],
    groupSeparatorBuilder: (String groupByValue) => Text(groupByValue),
    itemBuilder: (context, dynamic element) => Text(element['name']),
    itemComparator: (item1, item2) => item1['name'].compareTo(item2['name']), // optional
    useStickyGroupSeparators: true, // optional
    floatingHeader: true, // optional
    order: GroupedListOrder.ASC, // optional
  ),

参数

名称说明必需默认值
elements显示在列表中的数据列表必需-
groupBy用于匹配元素和其分组值的函数必需-
itemBuilder / indexedItemBuilder返回定义元素的函数。indexedItemBuilder 也提供了当前元素的索引。如果两者都定义了,会使用 indexedItemBuilder是,其中之一-
groupSeparatorBuilder / groupHeaderBuilder返回定义分组头部的函数。groupSeparatorBuilder 获取 groupBy- 值作为参数 groupHeaderBuilder 获取整个元素。如果两者都定义了,会使用 groupHeaderBuilder是,其中之一-
useStickyGroupSeparators设置为 true 时,当前可见分组的头部会固定在顶部非必需false
floatingHeader设置固定住的分组头部是漂在列表上层还是占用单独的空间非必需false
stickyHeaderBackgroundColor定义固定头部的背景色。只在启用 useStickyGroupSeparators 时可用。非必需Color(0xffF7F7F7)
separator定义分组中各个元素之间的分隔符非必需无分隔符
groupComparator可用于自定义分组的排序。否则使用自然排序的顺序非必需-
itemComparator可用于定义每个分组中元素的排序。否则使用自然排序的顺序非必需-
order改为 GroupedListOrder.DESC 可反转分组的排序非必需GroupedListOrder.ASC

ListView.builder 的属性项目也可使用

重点 - SilverGroupedList

现在支持基于滚动列表的分组列表。只需使用 SilverGroupedListView 代替 GroupedListView 。在 example/lib/example_silver 目录下可找到示例. 注意 GroupedListView 的一些选项现在在 SilverGroupedListView 中还不可用。

重点 - 聊天窗口

很容易就能创建聊天窗口。 只需要将 reverse 选项设置为 true ,将 order 设置为 GroupedListOrder.DESC。 在 examples 目录下可找到完整的示例。 列表会在初始化时自动滚动到最下方,因此滚动方向和阅读方向会是相反的。

我的其它库:

用于方便创建类聊天窗口:

查看我的 StickyGroupedList,基于 scrollable_positioned_list。