class MyApp extends StatelessWidget { const MyApp({Key key}) : super(key: key); @override Widget build(BuildContext context) { return MaterialApp( title: 'CheckedPopupMenuItem可勾选的弹出菜单', home: Scaffold( appBar: AppBar( title: Text('CheckedPopupMenuItem可勾选的弹出菜单'), ), body: DemoPage(), ), ); } } //CheckedPopupMenuItem可勾选的弹出菜单,常常与PopupMenuButton,作为PopupMenuButton构造方法的元素 class DemoPage extends StatefulWidget { DemoPage({Key key}) : super(key: key); @override _DemoPageState createState() => _DemoPageState(); } class _DemoPageState extends State<DemoPage> { List<String> _checkedValues; final String _checkedValue1 = '1'; final String _checkedValue2 = '2'; final String _checkedValue3 = '3'; final String _checkedValue4 = '4'; @override void initState() { //初始化选中的值 _checkedValues = <String>[_checkedValue1]; super.initState(); } bool isChecked(String value) => _checkedValues.contains(value); //将选中的值保存在 _checkedValues 中 void showCheckedMenuSelections(String value) { if (_checkedValues.contains(value)) { _checkedValues.remove(value); } else { _checkedValues.add(value); } } @override Widget build(BuildContext context) { return Container( color: Theme.of(context).primaryColor, child: ListTile( title: Text( '有选择标题的弹出菜单', style: TextStyle(color: Colors.white), ), trailing: PopupMenuButton<String>( padding: EdgeInsets.zero, onSelected: showCheckedMenuSelections, icon: Icon( Icons.menu, color: Colors.white, ), itemBuilder: (BuildContext context) => [ CheckedPopupMenuItem<String>( value: _checkedValue1, //是否选中,通过 isChecked 判断 _checkedValues 中是否保存 _checkedValue1 checked: isChecked(_checkedValue1), child: Text(_checkedValue1), ), CheckedPopupMenuItem<String>( value: _checkedValue2, //当前是否可选 enabled: false, checked: isChecked(_checkedValue2), child: Text(_checkedValue2), ), CheckedPopupMenuItem<String>( value: _checkedValue3, checked: isChecked(_checkedValue3), child: Text(_checkedValue3), ), CheckedPopupMenuItem<String>( value: _checkedValue4, checked: isChecked(_checkedValue4), child: Text(_checkedValue4), ), ], ), ), ); } }
Flutter笔记39:CheckedPopupMenuItem可勾选的弹出菜单
CheckedPopupMenuItem可勾选的弹出菜单,常常与PopupMenuButton,作为PopupMenuButton构造方法的元素: