gpt4 book ai didi

android - 在 Flutter 中为 DropdownMenu 使用枚举和 ValueNotifier

转载 作者:行者123 更新时间:2023-12-04 23:58:37 26 4
gpt4 key购买 nike

您好,我的目标是在下拉菜单中显示枚举值,并将 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com