Giter Club home page Giter Club logo

flutter-tree's Introduction

Flutter Tree

cover

GitHub stars pub package Run Test

Version1

Online Example

Install

dependencies:
  flutter_tree: ^2.0.0

Uasge

First Step

/// Your server data
final serverData = [
  {
    "checked": true,
    "children": [
      {
        "checked": true,
        "show": false,
        "children": [],
        "id": 11,
        "pid": 1,
        "text": "Child title 11",
      },
    ],
    "id": 1,
    "pid": 0,
    "show": false,
    "text": "Parent title 1",
  },
  {
    "checked": true,
    "show": false,
    "children": [],
    "id": 2,
    "pid": 0,
    "text": "Parent title 2",
  },
  {
    "checked": true,
    "children": [],
    "id": 3,
    "pid": 0,
    "show": false,
    "text": "Parent title 3",
  },
];

/// Map server data to tree node data
TreeNodeData mapServerDataToTreeData(Map data) {
  return TreeNodeData(
    extra: data,
    title: data['text'],
    expaned: data['show'],
    checked: data['checked'],
    children:
        List.from(data['children'].map((x) => mapServerDataToTreeData(x))),
  );
}

/// Generate tree data
List<TreeNodeData> treeData = List.generate(
  serverData.length,
  (index) => mapServerDataToTreeData(serverData[index]),
);

Basic

TreeView(data: treeData)

basic

Show Filter

TreeView(
  data: treeData,
  showFilter: true,
),

filter

Checked

TreeView(
  data: treeData,
  showCheckBox: true,
),

checked

Show Actions

/// Make sure pass `append` function.

TreeView(
  data: treeData,
  showActions: true,
  showCheckBox: true,
  append: (parent) {
    print(parent.extra);
    return TreeNodeData(
      title: 'Appended',
      expaned: true,
      checked: true,
      children: [],
    );
  },
),

actions

Bind Events

TreeView(
  data: treeData,
  showActions: true,
  showCheckBox: true,
  append: (parent) {
    return TreeNodeData(
      title: 'Appended',
      expaned: true,
      checked: true,
      children: [],
    );
  },
  onTap: (node) {
    print(node.extra);
  },
  onCheck: (checked, node) {
    print(checked);
    print(node.extra);
  },
  onCollapse: (node) {
    print(node.extra);
  },
  onExpand: (node) {
    print(node.extra);
  },
  onAppend: (node, parent) {
    print(node.extra);
    print(parent.extra);
  },
  onRemove: (node, parent) {
    print(node.extra);
    print(parent.extra);
  },
),

Lazy load

/// Create your load function, return list of TreeNodeData

Future<List<TreeNodeData>> _load(TreeNodeData parent) async {
  await Future.delayed(const Duration(seconds: 1));
  final data = [
    TreeNodeData(
      title: 'load1',
      expaned: false,
      checked: true,
      children: [],
      extra: null,
    ),
    TreeNodeData(
      title: 'load2',
      expaned: false,
      checked: false,
      children: [],
      extra: null,
    ),
  ];

  return data;
}

TreeView(
  data: treeData,
  lazy: true,
  load: _load,
  onLoad: (node) {
    print('onLoad');
    print(node.extra);
  },
),

load

All Props

property type default description required
data List<TreeNodeData> [] Tree data true
lazy bool false Lazy load node data false
icon Widget Icons.expand_more Tree icon false
offsetLeft double 24.0 Item padding left false
showFilter bool false Show tree filter false
showActions bool false Show node actions false
showCheckBox bool false Show node checkbox false
onTap Function(TreeNodeData) null Node tap callback false
onExpand Function(TreeNodeData) null Node expaned callback false
onLoad Function(TreeNodeData) null Node lazy load callback false
onCollapse Function(TreeNodeData) null Node collapse callback false
onCheck Function(bool, TreeNodeData) null Node check callback false
onAppend Function(TreeNodeData, TreeNodeData) null Node append callback false
onRemove Function(TreeNodeData, TreeNodeData) null Node remove callback false
append Function(TreeNodeData) null Append node data function false
load Future<List<TreeNodeData>> Function(TreeNodeData) null Load node data function false

TODO

  • Draggable tree
  • Custom filter function

Contribute

  1. Fork it (https://github.com/xrr2016/flutter_tree.git)
  2. Create your feature branch (git checkout -b feature/foo)
  3. Commit your changes (git commit -am 'Add some foo')
  4. Push to the branch (git push origin feature/foo)
  5. Create a new Pull Request

License

MIT

Stargazers over time

Stargazers over time

flutter-tree's People

Contributors

agostinofiscale avatar jackz314 avatar mauriziopinotti avatar tareq2 avatar vin-fandemand avatar xrr2016 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

flutter-tree's Issues

A request of publishing a new version

First of all, appreciate that you have done such an amazing repo. However, I figured out that there is a typo that expanded miss typed with expaned. I noticed that the PR to fix it has already been merged. I think it is better to release a new version, thanks!

New release on pub.dev?

Hi, is there gonna be a new release on pub.dev?

@xrr2016 Some PRs like #19 #20 #21 #22 #23 have been merged but not yet published, if you can't maintain this any more just let me know, I can take it over.

Thanks!

Error: The getter 'labelSmall' isn't defined for the class 'TextTheme'.

Flutter is updated to new versions and now TextTheme does not support lableSmall. Please update your Flutter SDKs and Flutter Plugins after that remove the obsolete code to make it useable with the most number of developers.

/C:/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_tree-2.0.2/lib/src/tree_node.dart:198:57: Error: The getter 'labelSmall' isn't defined for the class 'TextTheme'.

- 'TextTheme' is from 'package:flutter/src/material/text_theme.dart' ('/C:/flutter/packages/flutter/lib/src/material/text_theme.dart'). Try correcting the name to the name of an existing getter, or defining a getter or field named 'labelSmall'. Theme.of(context).textTheme.labelSmall?.fontSize,

/C:/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_tree-2.0.2/lib/src/tree_node.dart:212:57: Error: The getter 'labelSmall' isn't defined for the class 'TextTheme'.

- 'TextTheme' is from 'package:flutter/src/material/text_theme.dart' ('/C:/flutter/packages/flutter/lib/src/material/text_theme.dart'). Try correcting the name to the name of an existing getter, or defining a getter or field named 'labelSmall'. Theme.of(context).textTheme.labelSmall?.fontSize,

My Current Flutter Doctor Summary:

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.19041.1415], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1)
[√] IntelliJ IDEA Community Edition (version 2021.2)
[√] VS Code (version 1.52.1)
[√] Connected device (3 available)

• No issues found!

children动态变化的问题

我的需求是:点击树节点展开下一层级的时候,children 动态加载
实现方法是:在 tree_node 中添加了 didUpdateWidget 方法来监听 widget 变化
问题:目前只有第二级可以正常加载,第三级就监听不到 children 的变化了……

下面是相关代码:

这是生成TreeNode节点:

TreeNode(
          id: item['id'],
          parentId: item['parentId'],
          name: item['name'],
          count: item['count'] ?? 0,
          checked: item['checked'] ?? false,
          children: item['children'],  // 这个 item['children'] 是在点击展开的时候调用下面的 onExpand 动态赋值的
          onExpand: () {
            if (getDataFunc != null && getDataFunc is Function) {
              getDataFunc(item, i);  //这里会动态请求数据,然后赋值给children
            }
          },
        )

这是TreeNode class 中的 didUpdateWidget,点击展开第一级可以监听到children变化并正确展开第二级,但是点击第二级的时候就监听不到children变化了,children正确赋值了:

 @override
  void didUpdateWidget(MaterialTreeNode oldWidget) {
    if (oldWidget.children != widget.children && widget.children != null) {
      setState(() {
        _children = widget.children;
      });
    }
    super.didUpdateWidget(oldWidget);
  }

不知道我表述清楚了没,请教一下这么实现是ok的吗?为什么第三级不能正确展开呢?

添加节点能否动态填入内容?

您好,在进行添加子节点的时候,能否弹出对话框,或者设置我要添加的节点内容?或者是否已经实现了,有代码参考吗?

Hide expand icon option if the childrenList is null

I think that the children list should be nullable, so in that way we will be able to hide the arrow/expand icon.(example image below)
I used SIzedBox.shrink() and deactivate onExpand() as a replacement but the grey circle of touch feedback is still there.

Feed tree form http call

I have tried to feed the list from a http call but I am getting a subtype error :
Futrue<dynamic> is not List<TreeNodeData>.
The code :

  final response = await http.get
    (
      Uri.parse("uri"),
      headers: {"Accept": "application/json", "Content-Type": "application/json"}
  );
  final Iterable mapCollection = jsonDecode(response.body);

List<TreeNodeData> treeData = List.generate (
    mapCollection.length,
        (index) => mapServerDataToTreeData(mapCollection.toList()[index]),
  ).toList();

rtl not support

Does not support right to left
Please follow up quickly

Untitled.mp4

add this change to support null safety

Hi Guys ...
For anyone need to use this library with null safety support .. follow these steps :

First : copy files from root directory -> lib -> src and paste in your project

Secound : Go to tree_view.dart

change code in line 18 to this

 const TreeView({
    Key? key,  // add this line
    @required this.data,
    this.titleKey = 'title',
    this.leadingKey = 'leading',
    this.expanedKey = 'expaned',
    this.childrenKey = 'children',
    this.offsetLeft = 24.0,
    this.titleOnTap,
    this.leadingOnTap,
    this.trailingOnTap,
  }) : super(key: key);  // replace with this line

third : Go to tree_node.dart

change code in line 17 to this :

 const TreeNode({ 
    Key? key, // add this line
    this.level = 0,
    this.expaned = false, 
    this.offsetLeft = 24.0,
    this.children = const [],
    this.title = const Text('Title'),
    this.leading = const IconButton(
      icon: Icon(Icons.star_border),
      iconSize: 16,
      onPressed: null,
    ),
    this.trailing = const IconButton(
      icon: Icon(Icons.expand_more),
      iconSize: 16,
      onPressed: null,
    ),
    this.titleOnTap,
    this.leadingOnTap,
    this.trailingOnTap,
  }); : super(key: key); // replace with this line

in line 50 add this:

  @override // add this line
  initState() {
    _isExpaned = widget.expaned;
    _rotationController = AnimationController(
      duration: const Duration(milliseconds: 300),
      vsync: this,
    );
    super.initState();
  }

in line 90 and line 102 :

const SizedBox(width: 6.0), // add const
Expanded(
  child: GestureDetector(
    onTap: () {
      if (widget.titleOnTap != null &&
          widget.titleOnTap is Function) {
        widget.titleOnTap();
      }
    },
    child: widget.title ?? Container(),
  ),
),
const SizedBox(width: 6.0), // add const
Visibility(
  visible: children.isNotEmpty, // replace with isNotEmpty

in line 136 :

Visibility(
  visible: children.isNotEmpty && _isExpaned, // replace with isNotEmpty
  child: Padding(
    padding: EdgeInsets.only(left: level + 1 * offsetLeft),
    child: Column(
      children: widget.children,
      crossAxisAlignment: CrossAxisAlignment.start,
    ),
  ),
),

That's all 👍 👍 👍

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.