我认为Flutter中不存在这样的小部件,但是您可以自己构建。
在屏幕空间有限的手机上,显示带有提交按钮的对话框可能很有意义,例如本机Android对话框。
这是一个粗略的草图,说明如何用少于100行的代码实现这种对话框:
class MultiSelectDialogItem<V> { const MultiSelectDialogItem(this.value, this.label); final V value; final String label;}class MultiSelectDialog<V> extends StatefulWidget { MultiSelectDialog({Key key, this.items, this.initialSelectedValues}) : super(key: key); final List<MultiSelectDialogItem<V>> items; final Set<V> initialSelectedValues; @override State<StatefulWidget> createState() => _MultiSelectDialogState<V>();}class _MultiSelectDialogState<V> extends State<MultiSelectDialog<V>> { final _selectedValues = Set<V>(); void initState() { super.initState(); if (widget.initialSelectedValues != null) { _selectedValues.addAll(widget.initialSelectedValues); } } void _onItemCheckedChange(V itemValue, bool checked) { setState(() { if (checked) { _selectedValues.add(itemValue); } else { _selectedValues.remove(itemValue); } }); } void _onCancelTap() { Navigator.pop(context); } void _onSubmitTap() { Navigator.pop(context, _selectedValues); } @override Widget build(BuildContext context) { return alertDialog( title: Text('Select animals'), contentPadding: EdgeInsets.only(top: 12.0), content: SingleChildScrollView( child: ListTileTheme( contentPadding: EdgeInsets.fromLTRB(14.0, 0.0, 24.0, 0.0), child: ListBody( children: widget.items.map(_buildItem).toList(), ), ), ), actions: <Widget>[ FlatButton( child: Text('CANCEL'), onPressed: _onCancelTap, ), FlatButton( child: Text('OK'), onPressed: _onSubmitTap, ) ], ); } Widget _buildItem(MultiSelectDialogItem<V> item) { final checked = _selectedValues.contains(item.value); return CheckboxListTile( value: checked, title: Text(item.label), controlAffinity: ListTileControlAffinity.leading, onChanged: (checked) => _onItemCheckedChange(item.value, checked), ); }}
您可以像这样使用它:
void _showMultiSelect(BuildContext context) async { final items = <MultiSelectDialogItem<int>>[ MultiSelectDialogItem(1, 'Dog'), MultiSelectDialogItem(2, 'Cat'), MultiSelectDialogItem(3, 'Mouse'), ]; final selectedValues = await showDialog<Set<int>>( context: context, builder: (BuildContext context) { return MultiSelectDialog( items: items, initialSelectedValues: [1, 3].toSet(), ); }, ); print(selectedValues);}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)