flutter 使用递归构建无限层级树形结构

需求

1.树形选择类似于省市区选择 2.无限层级,省市区是三级循环不满足

出现场景

1.返回后端数据套娃时且数据类型及字段一样

2.无限层级树形分类

由于网上找不到现成的轮子,在经过不懈搜索后找到一个能看的过去的半成品轮子 flutter_simple_treeview(它是将json数据做了无限级别分裂(递归))但是还是不能满足项目预期

目标预期

步骤

  1. 拉下这个项目的源码,这里我已经拉下来了 码云仓库
  2. 作者插件库

2.先跑起来,他只是把json全部递归出来了

3.改下作者提供的demo

class TreeFromJson extends StatefulWidget {

   // 后端拿到的数据
  final List<dynamic> json;
  final Function callBack;

  TreeFromJson({Key? key, required this.json, required this.callBack}) : super(key: key);

  @override
  _TreeFromJsonState createState() => _TreeFromJsonState();
}

class _TreeFromJsonState extends State<TreeFromJson> {
  final TreeController _treeController = TreeController(allNodesExpanded: false);

  @override
  Widget build(BuildContext context) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        buildTree(),
      ],
    );
  }

  /// Builds tree or error message out of the entered content.
  Widget buildTree() {
    try {
      var parsedJson = widget.json;
      return Column(
        children: [
          TreeView(
            nodes: toTreeNodes(parsedJson),
            treeController: _treeController,
          )
        ],
      );
    } on FormatException catch (e) {
      return Text(e.message);
    }
  }

  List<TreeNode> toTreeNodes(dynamic parsedJson) {
    if (parsedJson is Map<String, dynamic>) {
      return parsedJson.keys.map((k) {
        // 就是这个地方用来显示下级 根据标志来判断他是最终要选的子集还是父类别,我这边如果是父类则继续递归
        if (k == 'children') {
          return TreeNode(
              content: Text('$k:${parsedJson[k]}'), children: toTreeNodes(parsedJson[k]));
        } else {
          return TreeNode();
        }
      }).toList();
    }

    if (parsedJson is List<dynamic>) {
      return parsedJson.asMap().map((i, element) =>
      // 就是这个地方判断下级 ,增加事件如果是最终要去的孩子则进行你要做的操作,反之则提示无下级孩子
          MapEntry(i,
              TreeNode(content:
              InkWell(
                onTap: () {
                  if (element['type'] == 'com') {
                    widget.callBack(element);
                  }else if(element['children'].length ==0){
                    Notice.showToast(text: "暂无下级");
                  }
                },
                child: Row(
                  children: [
                    SizedBox(
                      width: 200.w,
                      child: SingleChildScrollView(
                        scrollDirection: Axis.horizontal,
                        child: ConstrainedBox(
                          constraints: BoxConstraints(maxHeight: 140.w, maxWidth: 0.5.sw),
                          child: Container(
                              height: 40.h,
                              padding: EdgeInsets.only(left: 5.w),
                              decoration: UnderlineTabIndicator(
                                borderSide: BorderSide(width: 1.r, color: Color(0xFFEFF1F6)),
                              ),
                              <!-- 最终要拿到的孩子肯定是位于children里面的,从上一级的toTreeNodes里面递归出来 ,我们在这里只需要判断他是孩子还是父类的标志即可-->
                              child: Align(
                                alignment: Alignment.centerLeft,
                                child: element['type']==''?
                                Text('${element['name']}'):
                                treeContactItem(
                                    url: '${element['logo']}',
                                    title:element['name'],
                                    subtitle: element['type']
                                ),
                              )
                          ),
                        ),
                      ),
                    )
                  ],
                ),
              ), children: toTreeNodes(element['children']))))
          .values
          .toList();
    }
    return [TreeNode(content: Text(parsedJson.toString()))];
  }


  Widget treeContactItem({required String url,required String title, String? subtitle}){
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              ClipOval(
                child:  Commons.cachedNetwork(url: url,width: 28.r,height: 28.r)
              ),
              Container(
                margin: EdgeInsets.only(left: 9.r),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(title, style: TextThemes.textStyleGrey(size: 14)),
                    Text(subtitle??'暂无',style: TextThemes.textStyleGrey(color: const Color(0xFF999999)))
                  ],
                ),
              ),
            ],
          ),
          Container(
            width: 40.r,
            child: const Icon(Icons.keyboard_arrow_right, color: Color(0xCC666666)),
          )
        ],
      ),
    );
  }
}

3.改下作者的源码(/lib/src/node_widget.dart),改成这个吊样子

4.使用

pubspec.yaml
flutter_simple_treeview:        
    git:
      url: https://gitee.com/gsphelow/flutter_simple_treeview.git

SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: TreeFromJson(
    json: logic.list.value,
    callBack: (element) {
        if (Get.arguments['type'] == "select") {
        selectContact.addPerson(element);
        } else {
        Get.to(() => BusinessCardPage(),
            arguments: {"id": element['id'], 'type': 'enterprise'}
        );
        }
    },
    ),
)

5.最终效果

留言讨论