作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
您好,我的目标是在下拉菜单中显示枚举值,并将 setState 替换为 ValueNotifier 和 ValueListenableBuilder。我对 flutter 还很陌生,目前我只知道当我们有一个字符串列表及其使用 setState 时如何显示下拉菜单,但我该如何修改它。因此,例如我们有 enum Locations={belgium,germany,spain, etc}
到目前为止,这是我的代码:
class _TestState extends State<Test> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('hi'),
),
drawer: FoodNotifyDrawer('name'),
body: Container(
padding: EdgeInsets.all(7),
child: Center(
child: Column(
children: [
SizedBox(
height: 40,
),
DropdownButton(
// Not necessary for Option 1
value: _selectedLocation,
onChanged: (String? newValue) {
setState(() {
_selectedLocation = newValue;
});
},
items: _locations.map((location) {
return DropdownMenuItem(
child: Text(location),
value: location,
);
}).toList(),
),
SizedBox(
height: 40,
),
Text('Option 2'),
SizedBox(
height: 40,
),
],
),
),
),
);
}
}
任何帮助都会很棒,提前致谢:)
最佳答案
import 'package:flutter/material.dart';
enum Locations { belgium, germany, spain }
class DropDownTest extends StatelessWidget {
DropDownTest({Key? key}) : super(key: key);
final ValueNotifier<Locations> _selectedValue =
ValueNotifier<Locations>(Locations.belgium);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ValueListenableBuilder<Locations>(
valueListenable: _selectedValue,
builder: (context, v, _) {
return DropdownButton<Locations>(
value: v,
onChanged: (Locations? newValue) {
if (newValue != null) {
_selectedValue.value = newValue;
}
},
items: Locations.values.map((d) {
return DropdownMenuItem(
child: Text(d.name),
value: d,
);
}).toList(),
);
}),
),
);
}
}
关于android - 在 Flutter 中为 DropdownMenu 使用枚举和 ValueNotifier,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71311921/
我是一名优秀的程序员,十分优秀!