wiradikusuma
wiradikusuma

Reputation: 1909

Flutter DropdownButton inside TextFormField as prefix

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.

How to do it?

TextFormField(
    initialValue: '10.00',
    decoration: InputDecoration(
        prefix: DropdownButtonHideUnderline(
            child: DropdownButton(
                items: CURRENCY_CODES,
                onChanged: _onCurrencyChanged,
                value: _currency,
            ),
        ),
    ),
),

Upvotes: 1

Views: 7257

Answers (1)

Pablo Barrera
Pablo Barrera

Reputation: 10963

The Problem

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.

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.


The Solution

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.


The Implementation

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

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(),
          ),
        ],
      ),
    ),
  ],
)

Upvotes: 3

Related Questions