我正在尝试创建一个包含可选单选按钮的弹出菜单,以更改 View 类型(例如图库、卡片、滑动、网格、列表等)。
我遇到的问题是 PopupMenu 有自己的用于选择值的回调,Radio 和 RadioListTile 也是如此。
这是我的第一次尝试。这实际上有效,只是按钮永远变灰。给 RadioListTiles 一个非空的 noop 函数会导致按钮不再灰显(禁用),但弹出菜单不再起作用。
new PopupMenuButton<String>(
...
itemBuilder: (ctx) => <PopupMenuEntry<String>>[
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Cards"),
value: 'cards',
groupValue: _view,
onChanged: null),
value: 'cards'),
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Swipe"),
value: 'swipe',
groupValue: _view,
onChanged: null),
value: 'swipe'),
],
onSelected: (String viewType) {
_view = viewType;
}));
第二次尝试是完全忽略 PopupMenu,只使用 RadioListTile onChanged
。这些按钮不是灰显/禁用的,但也不起作用。
new PopupMenuButton<String>(
...
itemBuilder: (ctx) => <PopupMenuEntry<Null>>[
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Cards"),
value: 'cards',
groupValue: _view,
onChanged: (v) => setState(() => _view = v)),
value: 'cards'),
new PopupMenuItem(
child: new RadioListTile(
title: new Text("Swipe"),
value: 'swipe',
groupValue: _view,
onChanged: (v) => setState(() => _view = v)),
value: 'swipe'),
],
));
正确的方法是什么? PopupMenu 适用于极其简单的菜单,但元素选择给我带来了冲突。有没有办法获得一个“愚蠢”的弹出菜单,在按钮上显示一列小部件(样式像菜单)?
最佳答案
我认为对您来说最好的解决方案是使用 CheckedPopupMenuItems而不是广播列表。功能应该正是您想要实现的,不是吗?
这是一个小例子:
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _selectedView = 'Card';
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('TestProject'),
actions: <Widget>[
new PopupMenuButton(
onSelected: (value) => setState(() => _selectedView = value),
itemBuilder: (_) => [
new CheckedPopupMenuItem(
checked: _selectedView == 'Card',
value: 'Card',
child: new Text('Card'),
),
new CheckedPopupMenuItem(
checked: _selectedView == 'Swipe',
value: 'Swipe',
child: new Text('Swipe'),
),
new CheckedPopupMenuItem(
checked: _selectedView == 'List',
value: 'List',
child: new Text('List'),
),
],
),
],
),
body: new Center(child: new Text(_selectedView)),
);
}
}
https://stackoverflow.com/questions/44085543/
相关文章:
dart - StreamBuilder 会在无状态小部件中自动关闭流吗?
ios - 如何在 iOS 中安装用 Flutter 编写的应用程序?
flutter - 如何在 Flutter Web 中保存到 Web 本地存储
flutter - TabBarView 中的 GestureDetector - 嵌套滚动?
dart - 在 CustomScrollView 中使用 StreamBuilder 和 Sliv
dart - 在 Flutter 中查找和版本化过时的包(跨主要版本)
dart - 在 Flutter 应用程序中存储外观和指标常量