dictionary - 在 Flutter 中使用 Map 制作下拉菜单
问题描述
所以我想在颤动中创建一个对象,它将 aMap<String, int>
作为值列表,其中String
是菜单中显示的内容,并且int
存储在类中以供选择项目后使用。
我不确定该怎么做。涉及返回int
值的部分让我难以理解。
地图结构是这样写的:
final Map<String, int> discBasis = {
'Age': 1,
'Ancestry': 2,
'Color': 3,
'Disability': 4,
'Race': 5,
'Religion': 6,
'Sex': 7,
'Familial Status': 8,
'National Origin': 9
};
&我目前正在使用的课程:
final double formMarginHoriz = 10.0;
final double formMarginVert = 5.0;
class DropDownFromMap extends StatefulWidget {
Map<String, int> kv;
DropDownFromMap(this.kv);
@override
DropDownFromMapState createState() => new DropDownFromMapState(kv);
}
class DropDownFromMapState extends State<DropDownFromMap> {
Map<String, int> kv;
DropDownFromMapState(this.kv);
int selectedVal;
@override
Widget build(BuildContext context) {
return new Container(
margin: EdgeInsets.only(
top: formMarginVert,
bottom: formMarginVert,
left: formMarginVert,
right: formMarginHoriz),
child: new DropdownButton<int>(
hint: new Text("Select an option"),
value: selectedVal,
onChanged: (String newVal) {
setState(() {
selectedVal = kv[newVal];
});
},
items: kv.map((String k, _) {
return new DropdownMenuItem<String>(
value: k,
child: new Text(k),
);
}).toList(),
));
}
}
它是这样实例化的(这可能是错误的):
@override
Widget build(BuildContext context) {
return new Material(
color: Colors.blueAccent,
child: new Container(
child: new Form(
key: _formKey,
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new DropDownFromMap(data.offenderType),
...
更多上下文可以在 github 项目中找到:https://github.com/chscodeforchange/icrc-app在相关文件中:dropdown.dart
, off_page_one.dart
, & form_data.dart
。
先感谢您!
解决方案
static const Map<String, Duration> frequencyOptions = {
"30 seconds": Duration(seconds: 30),
"1 minute": Duration(minutes: 1),
"2 minutes": Duration(minutes: 2),
};
Duration _frequencyValue = Duration(seconds: 30);
@override
Widget build(BuildContext context) {
return DropdownButton<Duration>(
items: frequencyOptions
.map((description, value) {
return MapEntry(
description,
DropdownMenuItem<Duration>(
value: value,
child: Text(description),
));
})
.values
.toList(),
value: _frequencyValue,
onChanged: (Duration? newValue) {
if (newValue != null) {
setState(() {
_frequencyValue = newValue;
});
}
},
);
}
推荐阅读
- html - 使用xpath获取href链接的内部href
- javascript - TypeError:无法读取未定义 discord.js 的属性“执行”
- typescript - 如何根据字符串值检查泛型类型映射器是否具有键
- android - 如何将 ArrayList 转移到另一个活动
- angular - 如何编写角度单元测试以在按钮单击时呈现子组件
- go - 从opentelemetry的请求标头中提取跟踪器的正确方法
- flutter - “没有引用声明‘setState’。” StatefulWidget 中 DropdownButton 的警告
- python - 噪声图像上的Opencv矩形检测
- azure - 是否可以使用应用程序网关在 AKS 中同时公开 HTTP 端口和 TCP 端口?
- java - 是否可以获取布局的 id 并在 ViewHolder 类中进行比较?