TextFormField中的Flutter DropdownButton作为前缀 [英] Flutter DropdownButton inside TextFormField as prefix
问题描述
按标题,我想在TextFormField
内添加DropdownButton
作为prefix
(或prefixIcon
?).文本字段用于金额,下拉列表用于其货币.
As per title, I want to add a DropdownButton
inside a TextFormField
as prefix
(or prefixIcon
?). The text field is for amount, and the dropdown is for its currency.
我的直截了当的方法在视觉上有效,但是我无法点击下拉列表来显示列表.每次点击它时,它将显示(并立即隐藏)文本字段本身的键盘.
My straightforward approach works visually, but I can't tap the dropdown to show the list. Every time I tap it, it will show (and immediately hide) the keyboard for the text field itself.
该怎么做?
TextFormField(
initialValue: '10.00',
decoration: InputDecoration(
prefix: DropdownButtonHideUnderline(
child: DropdownButton(
items: CURRENCY_CODES,
onChanged: _onCurrencyChanged,
value: _currency,
),
),
),
),
推荐答案
问题
当您点击prefix
中包含的Widget
时,TextFormField
将聚焦并出现键盘.但是由于Widget
是DropdownButton
,因此当显示DropdownItems
时,键盘被关闭,而奇怪的是,DropdownItems
也被关闭了.
When you tap on the Widget
contained on prefix
, the TextFormField
will focus and the keyboard will appear. But since the Widget
is a DropdownButton
, when the DropdownItems
are shown the keyboard is dismissed and strangely the DropdownItems
are dismissed too.
如果尝试使用PopupMenuButton
而不是DropdownButton
,则会发生类似的情况:先显示键盘,然后将其关闭,但在这种情况下,不会关闭PopupMenuItems
.为此,我可以使用焦点侦听器和标志来解决,但这不是很好.
If you try to use PopupMenuButton
instead of DropdownButton
, something similar happens: the keyboard is shown and then dismissed but in this case the PopupMenuItems
aren't dismissed. For this I could have a workaround using focus listeners and flags, but is not good.
解决方案
采用另一种方法,一种方法是将Container
与所需的装饰一起使用,包装包含DropdownButton
/PopupMenuButton
和TextFormField
的Row
.
Take another approach, one way could be to use a Container
with the decoration you want, wrapping a Row
that contains a DropdownButton
/ PopupMenuButton
and the TextFormField
.
实施
如果与DropdownButton
一起使用,则在聚焦TextFormField
并点击DropdownButton
时,键盘将被关闭,而奇怪的是,DropdownItems
也将被关闭.这是一个未解决的问题:当点击并显示键盘时,DropdownButton行为不良
If you go with a DropdownButton
, when you focus the TextFormField
and then you tap the DropdownButton
, the keyboard will be dismissed and strangely the DropdownItems
are dismissed too. This is an unresolved issue: DropdownButton bad behaviour when tapped and keyboard is showing
如果您使用PopupMenuButton
,则可以执行以下操作:
If you go with a PopupMenuButton
, you could do something like this:
Wrap(
children: <Widget>[
Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(16.0),
boxShadow: [BoxShadow()],
),
child: Row(
children: <Widget>[
PopupMenuButton(
onSelected: (c) {},
child: Row(
children: <Widget>[
Text(_currency),
Icon(Icons.arrow_drop_down)
],
),
itemBuilder: (context) => CURRENCY_CODES
.map((c) => PopupMenuItem(value: c, child: Text(c)))
.toList(),
),
Flexible(
child: TextFormField(),
),
],
),
),
],
)
这篇关于TextFormField中的Flutter DropdownButton作为前缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!