DropdownMenu
可實現下拉選單。
Version
Flutter 3.24
Flutter
- Android 與 iOS 都成功使用
DropdownMenu
顯示
DropdownMenu
import 'package:flutter/material.dart';
class Home extends StatefulWidget {
const Home({super.key});
State<Home> createState() {
return _Home();
}
}
class _Home extends State<Home> {
int? _selectedValue = 1;
Widget build(BuildContext context) {
var appBar = AppBar(
title: const Text('DropdownMenu'),
);
var dropdownMenuEntries = const [
DropdownMenuEntry<int>(value: 1, label: 'One'),
DropdownMenuEntry<int>(value: 2, label: 'Two'),
DropdownMenuEntry<int>(value: 3, label: 'Three'),
];
var dropdownMenu = DropdownMenu<int>(
initialSelection: 1,
onSelected: (int? newValue) {
setState(() {
_selectedValue = newValue;
});
},
dropdownMenuEntries: dropdownMenuEntries,
);
var selectedValue = Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text('$_selectedValue'),
);
var body = Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Row(
children: [
dropdownMenu,
selectedValue,
],
),
);
return Scaffold(
appBar: appBar,
body: body,
);
}
}
Line 12
class _Home extends State<Home> {
}
DropdownButton
必須搭配StatefulWidget
Line 13
int? _selectedValue = 1;
_selectedValue
:定義 state 取得目前用戶所選擇的項目
Line 27
var dropdownMenu = DropdownMenu<int>(
initialSelection: 1,
onSelected: (int? newValue) {
setState(() {
_selectedValue = newValue;
});
},
dropdownMenuEntries: dropdownMenuEntries,
);
DropdownMenu
:建立下拉選單,必須使用泛形
指定用戶所選擇項目的型別
initialSelection
:設定DropdownMenu
的初始值onSelected()
:當用戶改變所選擇項目是觸發事件,將值寫入 statedropdownMenuEntries
:設定下拉選單項目
Line 21
var dropdownMenuEntries = const [
DropdownMenuEntry<int>(value: 1, label: 'One'),
DropdownMenuEntry<int>(value: 2, label: 'Two'),
DropdownMenuEntry<int>(value: 3, label: 'Three'),
];
DropDownMenuEntry
:建立下拉選單項目value
:選單值label
:選單文字
Line 37
var selectedValue = Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Text('$_selectedValue'),
);
Text
:顯示目前用戶所選擇項目的值
Conclusion
- 因為要使用 state 記住目前用戶所選擇的項目,所以必須搭配
StatefulWidget
- 因為
DropdownMenuEntry
的選單文字
為label
只能為 String,因此DropdownMenu
沒辦法如DropdownButton
實現兩層下拉選單