Search code examples
flutterdrop-down-menutreeviewdropdown

How to make Tree Select Box with DropdownButton in flutter


I want to make a Select box with DropDownButton in Flutter. but I can not make a perfect algorithm for it. I hope to receive great help from Flutter experts. Thank you.

Screenshot of current implementation


Solution

  • I already solved this problem myself. Here is my code. But I expect a better solution of Flutter experts.

      addTaskList(){
    taskChildrenList.clear();
    print(selectedTaskList.length);
    selectedTaskList.forEach((task){
      taskChildrenList.add(Card(
        margin: EdgeInsets.symmetric(vertical: 5),
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 8),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Text("${AppLanguage.selectTaskLabel()} ${task[0].label}",style: TextStyle(fontSize: 15,fontWeight: FontWeight.bold),),
              Flexible(
                child: FittedBox(
                  child: DropdownButton<JustificationTask>(
                    value: selectedTasks.length==task[0].label-1?null:selectedTasks[task[0].label-1],
                    icon: Icon(Icons.chevron_right),
                    iconSize: 25,
                    elevation: 16,
                    style: TextStyle(color: Colors.black),
                    underline: Container(height: 1, color: Colors.transparent,),
                    onChanged: (JustificationTask value) {
                      setState(() {
                        selectedTaskList.removeRange(value.label, selectedTaskList.length);
                        selectedTasks.removeRange(value.label-1, selectedTasks.length);
                        selectedTasks.add(value);
                        if(value.children.isNotEmpty){
                          selectedTaskList.add(value.children);
                          selectedTask=null;
                        }else{
                          selectedTask=value;
                          equipment=null;
                        }
                      });
                    },
                    items: task.map<DropdownMenuItem<JustificationTask>>((JustificationTask value) {
                      return DropdownMenuItem<JustificationTask>(
                        value: value,
                        child: SizedBox(width:MediaQuery.of(context).size.width*0.4,child: Text("${taskName(value)}",style: TextStyle(fontSize: 20),)),
                      );
                    }).toList(),
                    hint: SizedBox(width:MediaQuery.of(context).size.width*0.4,child: Text(AppLanguage.task(),style: TextStyle(fontSize: 20))),
                    isExpanded: false,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),);
    });
    

    }