'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.
Solution 1:[1]
For anyone else running into this problem and not being helped by the answers here... I wrote a simple app that does exactly this, select an item from a tree using dynamic dropdown buttons. Here's the entire code:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class Node {
final String name;
final List<Node> children;
Node({this.name, this.children});
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(title: 'Animal Classification'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> treeLevels = ['Phylum', 'Class', 'Species'];
List<Node> selectedNodes = [
Node(name: 'Animal Kingdom', children: <Node>[
Node(name: 'Vertebrates', children: <Node>[
Node(name: 'Fish'),
Node(name: 'Amphibians'),
Node(name: 'Reptiles'),
Node(name: 'Birds'),
Node(name: 'Mammals', children: <Node>[
Node(name: 'Bats'),
Node(name: 'Carnivores'),
Node(name: 'Birds'),
]),
]),
Node(name: 'Annelids'),
Node(name: 'Molluscs'),
Node(name: 'Nematodes'),
Node(name: 'Arthropods', children: <Node>[
Node(name: 'Crustaceans'),
Node(name: 'Arachnids'),
Node(name: 'Insects'),
Node(name: 'Myriapods'),
]),
]),
];
@override
Widget build(BuildContext context) {
List<Widget> items = [];
for (var i = 0; i < selectedNodes.length; i++) {
if (selectedNodes[i] != null &&
(selectedNodes[i].children?.isNotEmpty ?? false)) {
items.add(
Text(treeLevels[i], style: Theme.of(context).textTheme.headline5));
items.add(DropdownButtonFormField(
value: selectedNodes.length > i + 1 ? selectedNodes[i + 1] : null,
items: selectedNodes[i]
.children
.map((node) => DropdownMenuItem(
value: node,
child: Text(node.name),
))
.toList(),
onChanged: (selected) => setState(() {
selectedNodes.removeRange(i + 1, selectedNodes.length);
selectedNodes.add(selected);
}),
));
items.add(SizedBox(height: 16.0)); // Padding
}
}
return Scaffold(
appBar: AppBar(
title: Center(child: Text(widget.title)),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: ListView(
children: items,
),
));
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SakoDaemon |