flutter - 如何将弹出菜单按钮中的选定项目显示为文本?
问题描述
我有一个弹出菜单按钮,下面有一个文本小部件。我希望文本小部件显示用户从弹出菜单按钮中选择的内容。
弹出菜单按钮未按下
弹出菜单按钮按下
现在在_mlTextWidget()
下面我只能弄清楚如何硬编码特定的选择。
我不确定如何将所选项目与文本小部件连接起来。任何帮助将不胜感激。
// A class containing the menu items
class MLConstants {
static const String FourX = '4x';
static const String TenX = '10x';
static const String TwentyFiveX = '25x';
static const String FourtyX = '40x';
static const String SixtyThreeX = '63x';
static const List<String> choices3 = <String>[
FourX,
TenX,
TwentyFiveX,
FourtyX,
SixtyThreeX
];
}
// Popup menu button
Widget _cameraTogglesRowWidget() {
return PopupMenuButton<String>(
icon: const Icon(
Icons.zoom_in,
color: Colors.white,
size: 30,
),
onSelected: choiceAction3,
itemBuilder: (BuildContext context) {
return MLConstants.choices3.map((String choice3) {
return PopupMenuItem<String>(
value: choice3,
child: Text(choice3),
);
}).toList();
},
);
}
// What happens when a menu item is pressed
void choiceAction3(String choice3) {
if (choice3 == MLConstants.FourX) {
print('4x');
} else if (choice3 == MLConstants.TenX) {
print('10x');
} else if (choice3 == MLConstants.TwentyFiveX) {
print('25x');
} else if (choice3 == MLConstants.FourtyX) {
print('40x');
} else if (choice3 == MLConstants.SixtyThreeX) {
print('63x');
}
}
// The text widget showing the selected item
Widget _mlTextWidget() {
return Container(
child: (Text("${MLConstants.FourX}",
style: TextStyle(
fontSize: 13,
color: Colors.white,
))));
}
解决方案
您需要将其置于状态onSelected
并在您的Text
. 像这样:
String selectedChoice3;
void choiceAction3(String choice3) {
setState(() {
selectedChoice3 = choice3;
});
if (choice3 == MLConstants.FourX) {
print('4x');
} else if (choice3 == MLConstants.TenX) {
print('10x');
} else if (choice3 == MLConstants.TwentyFiveX) {
print('25x');
} else if (choice3 == MLConstants.FourtyX) {
print('40x');
} else if (choice3 == MLConstants.SixtyThreeX) {
print('63x');
}
}
// The text widget showing the selected item
Widget _mlTextWidget() {
return Container(
child: (Text("${selectedChoice3 ?? ''}",
style: TextStyle(
fontSize: 13,
color: Colors.white,
))));
}
当然,假设这些都在一个State
类中。如果没有,您可以在IntelliJ或VSCode中自动将您的转换StatelessWidget
为 a 。StatefulWidget
推荐阅读
- typescript - 如何删除自定义声明
- rake - Rails v6.0.0 推送到 Heroku 失败 - Rake & Bundler 错误消息
- generics - 方法接收共享相同继承类的类引用
- go - 我想在接收命令行输出的同时接收命令行输入
- angular - Angular 7 + Feathersjs 仅将更新的对象作为数组返回
- python - 为什么梯度下降在 pytorch 中不能按预期工作
- powershell - 如何防止 PowerShell -Recurse 两次重命名第一个文件?
- java - Spring 5.1.5.RELEASE 我应该怎么想选择一个 JVM 版本
- c# - 如何检测表单何时从一个屏幕更改为另一个屏幕
- python - 亚马逊价格网络抓取问题与 python、请求和 bs4