點燈坊

失くすものさえない今が強くなるチャンスよ

DropdownMenu 實現下拉選單

Sam Xiao's Avatar 2024-10-17

DropdownMenu 可實現下拉選單。

Version

Flutter 3.24

Flutter

overview

  • Android 與 iOS 都成功使用 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():當用戶改變所選擇項目是觸發事件,將值寫入 state
    • dropdownMenuEntries:設定下拉選單項目

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 實現兩層下拉選單