flutter 三级下拉菜单
时间: 2024-08-06 22:00:40 浏览: 107
在Flutter中实现三级下拉菜单通常涉及到递归调用或者使用嵌套的`PopupMenuButton`结构。这里我们先从基本的二级菜单开始,然后扩展到三级菜单:
**一级菜单示例**[^1]:
```dart
import 'package:flutter/material.dart';
class DropdownMenu extends StatelessWidget {
final List<String> items;
DropdownMenu({required this.items});
@override
Widget build(BuildContext context) {
return PopupMenuButton<String>(
itemBuilder: (context) => items.map((item) => DropdownMenuItem<String>(
child: Text(item),
value: item,
)).toList(),
onSelected: (value) {},
);
}
}
```
**二级菜单示例**(假设一级菜单选择后触发二级菜单):
```dart
class NestedDropdown extends StatefulWidget {
final Function(String) onChanged;
NestedDropdown({required this.onChanged});
@override
_NestedDropdownState createState() => _NestedDropdownState();
}
class _NestedDropdownState extends State<NestedDropdown> with SingleTickerProviderStateMixin {
bool _isShowingSecondLevel = false;
final List<String> secondLevelItems = ['Option 1', 'Option 2'];
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_isShowingSecondLevel = !_isShowingSecondLevel;
});
},
child: Row(
children: [
DropdownButton<String>(
value: "",
onChanged: widget.onChanged,
items: firstLevelItems.map((item) =>
DropdownMenuItem<String>(
child: Text(item),
value: item,
onPressed: () {
if (_isShowingSecondLevel) {
// 展示二级菜单
} else {
// 第一级菜单选择后关闭二级菜单
}
},
),
).toList(),
),
SizedBox(width: 16), // 间距调整以适应二级菜单
if (_isShowingSecondLevel)
Expanded(child: DropdownMenu(items: secondLevelItems)),
],
),
);
}
}
```
要实现真正的三级菜单,你可以继续沿用这个思路,添加一个内部类来代表第三级菜单,当二级菜单项被选中时显示。
阅读全文