flutter - How to set DropdownButton's value programmatically?
问题描述
For example, in order to set the text in a TextFormField
, I can use a TextEditingController
:
textEditingController = TextEditingController()
...
TextFormField(
controller: textEditingController
);
...
textEditingController.text = 'my text'; // This is where I can set the text in the TextFormField
Is there a similar way to programmatically set the selection in a DropdownButton
? As far as I know, simply setting the value
field in a DropdownButton
won't suffice since the change won't be applied without calling the setState
from the wrapping state
object.
解决方案
正如@CopsOnRoad 评论的那样,这里似乎没有捷径,setState
必须调用才能反映DropdownButton
所选值的变化。问题是,setState
所以protected
我需要通过一些循环来确保在需要时调用它。我最终通过实现一个DropdownButton
状态为监听器的通知器来做到这一点。类似于以下内容:
class MyStatefulWidget extends StatefulWidget {
final _valueNotifier = ValueNotifier<String>(null);
@override
State<StatefulWidget> createState() => MyState(_valueNotifier);
// This exposes the ability to change the DropdownButtons's value
void setDropdownValue(String value) {
// This will notify the state and will eventually call setState
_valueNotifier.value = value;
}
}
class MyState extends State<MyStatefulWidget> {
String _selection;
MyState(ValueNotifier<String> valueNotifier) {
valueNotifier.addListener(() {
setState(() {
_selection = valueNotifier.value;
});
});
}
@override
Widget build(BuildContext context) {
return DropdownButton<String>(
items: [
DropdownMenuItem<String>(
value: "1",
child: Text(
"1",
),
),
DropdownMenuItem<String>(
value: "2",
child: Text(
"2",
),
)
],
onChanged: (value) {
setState(() {
_selection = value;
});
},
value: _selection,
);
}
}
推荐阅读
- php - 获取 Ajax POST URL
- json - 标识符中带有点的 Jekyll 站点数据
- javascript - Firebase Cloud Functions 无法写入 Firestore 数据库 - 权限缺失或不足
- c# - 手模型内轴旋转统一
- python - 带有类别列表的 Flash Flasks 消息到 HTML5 jinja2 模板
- java - 如何创建一组字符串,其中每个字符串有 1000 个客户 ID 用于 Oracle 查询表达式
- c# - 构建时游戏 UI 位置更改,而在具有相同分辨率的统一编辑器中工作正常
- debian - Gitlab-ci,图像 debian:jessie。无法使用 su 命令更改用户
- c# - 用于 C# 桌面应用程序的数据库
- c# - 从 int[] 中选择每 2 个整数,并使用 Lamda 表达式将它们组合成一个 uint64[] 数组