請問,我怎樣才能做到這一點:

試了很多次都失敗了
List<String> list = [
"Topic 1",
" Sub Topic 1",
" Sub Topic 2",
" Sub Topic 3",
" Sub Topic 4",
"Topic 2",
" Sub Topic 1",
" Sub Topic 2",
"Topic 3",
" Sub Topic 1",
" Sub Topic 2",
" Sub Topic 3",
];
感謝您...
uj5u.com熱心網友回復:
您需要以嵌套方式表示您的資料。目前您的串列并不代表這一點,并且使用給定串列創建小部件并不容易。
例如,您可以創建一個資料物件,例如:
class Topic {
final String text;
final List<Topic> subTopics = [];
Topic({required this.text, List<Topic> subTopics = const []}) {
this.subTopics.addAll(subTopics);
}
}
然后創建一個Topics 串列,例如:
final topics = <Topic>[
// topic 1
Topic(
text: 'Topic 1',
subTopics: [
Topic(text: 'Sub Topic 1'),
Topic(
text: 'Sub Topic 2',
subTopics: [
Topic(
text: 'sub sub topic 1',
),
],
),
Topic(text: 'Sub Topic 3'),
],
),
// topic 2
Topic(
text: 'Topic 2',
subTopics: [
Topic(
text: 'Sub Topic 1',
),
Topic(
text: 'Sub Topic 2',
),
],
),
// topic 3
Topic(
text: 'Topic 3',
)
];
最后在您的小部件中,您可以像這樣構建它:
class NestedTopicWidget extends StatelessWidget {
const NestedTopicWidget({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: topics.length,
itemBuilder: (context, index) {
return TopicWidget(topic: topics[index]);
},
);
}
}
class TopicWidget extends StatelessWidget {
final Topic topic;
const TopicWidget({Key? key, required this.topic}) : super(key: key);
@override
Widget build(BuildContext context) {
return ExpansionTile(
title: Text(topic.text),
children: List.generate(topic.subTopics.length, (index) => TopicWidget(topic: topic.subTopics[index])),
);
}
}
結果是:

這是一個完全可運行的示例,您可以在 DartPad 上查看:https ://dartpad.dev/ ? id = 6802f0f362f0c408b149715ce3e8590b
uj5u.com熱心網友回復:
更新
對于簡單的情況,您會回圈,正如您評論使用 ListView。
ListView(
children: [
...List.generate(
list.length,
(index) => Column(
children: [
if (index != 0 &&
index != list.length - 1 &&
!list[index].contains("Sub"))
Divider(),
ListTile(
title: Text(list[index]),
trailing: list[index].contains("Sub")
? null
: Icon(Icons.arrow_drop_down),
),
],
),
)
],
)
對于這種情況,我喜歡使用Map.
final Map<String, List<String?>> data = {
"Topic 1": [
" Sub Topic 1",
],
" Sub Topic 2": [
" SubSub Topic 1",
],
"Topic 2": [
" Sub Topic 1",
" Sub Topic 2",
],
"Topic 3": []
};
對于 UI,我正在使用 ExpansionTile
...data.keys.map(
(k) => ExpansionTile(
expandedAlignment: Alignment.centerLeft,
title: Text(k),
children: data[k] == null
? [
const SizedBox(),
]
: data[k]!
.map(
(e) => Text(e ?? ""),
)
.toList(),
),
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/420289.html
標籤:
