Horizontal Tree Selector

一个 Flutter 横向多级树形结构选择器组件,支持无限层级的数据选择。

pub package license platform style: flutter lints

效果预览

效果演示

特性

  • 🎯 横向多列展示,直观清晰
  • 🔄 支持固定模式和动态模式
  • 🎨 支持自定义主题颜色
  • ✨ 自动选中子级第一项
  • 📍 支持预选项路径回显
  • 📱 适配移动端底部弹窗

安装

pubspec.yaml 中添加依赖:

dependencies:
  horizontal_tree_selector: ^0.0.1

然后运行:

flutter pub get

使用方法

1. 定义数据模型

使用内置的 OptionChildrenItemImpl 或实现 OptionChildrenItem 接口:

final options = [
  OptionChildrenItemImpl(
    name: '电子产品',
    value: '1',
    children: [
      OptionChildrenItemImpl(
        name: '手机',
        value: '1-1',
        children: [
          OptionChildrenItemImpl(name: 'iPhone', value: '1-1-1', children: null),
          OptionChildrenItemImpl(name: '华为', value: '1-1-2', children: null),
        ],
      ),
    ],
  ),
];

2. 调用选择器

final result = await showHorizontalMultiLevelTreePopup(
  context: context,
  options: options,
  title: '请选择分类',
  themeColor: Colors.blue,
  onConfirm: (selectedPath, finalSelected) {
    print('选择路径: $selectedPath');
    print('最终选中: $finalSelected');
  },
);

API 参数

参数 类型 必填 说明
context BuildContext 上下文
options List<T> 树形选项列表
selectedItem T? 当前选中项(用于回显)
title String 弹窗标题,默认 "请选择"
levelTitles List<String>? 每级标题,空时启用动态模式
themeColor Color? 主题颜色
onConfirm Function? 确定回调
onCancel VoidCallback? 取消回调
confirmText String 确定按钮文本,默认 "确定"
cancelText String 取消按钮文本,默认 "取消"

两种模式

固定模式

levelTitles 不为空时启用,显示固定数量的列:

showHorizontalMultiLevelTreePopup(
  context: context,
  options: options,
  levelTitles: ['省份', '城市', '区县'],  // 固定3列
);

动态模式

levelTitles 为空或不传时启用,根据数据深度自动调整列数:

showHorizontalMultiLevelTreePopup(
  context: context,
  options: options,
  // 不传 levelTitles,自动适应数据层级
);

自定义数据模型

实现 OptionChildrenItem 抽象类:

class MyCategory extends OptionChildrenItem {
  final int id;
  
  MyCategory({
    required this.id,
    required String name,
    List<MyCategory>? children,
  }) : super(
    name: name,
    value: id.toString(),
    children: children,
  );
}

License

MIT License

Libraries

horizontal_tree_selector
横向多级树形结构选择器组件库