How can I display a hint text in a TextField
if it contains only space characters like ' '
?
const TextField(
decoration: InputDecoration(
hintText: 'a hint text'
),
),
In this code example the hint text is only displayed if the content of the TextField
is empty.
I need this because I need to detect when the user press the backspace button on an empty TextField
. Read more here: https://medium.com/super-declarative/why-you-cant-detect-a-delete-action-in-an-empty-flutter-text-field-3cf53e47b631
CodePudding user response:
After diving deeper into the problem I found a solution with InputDecorator
:
const InputDecorator(
isEmpty: true, // if true, the hint text is shown
decoration: InputDecoration(
hintText: 'a hint text'
),
child: TextField(),
),
So my solution is this:
String _value = ''; // state variable
...
InputDecorator(
isEmpty: _value.trim().isEmpty, // override the default isEmpty behavior
decoration: const InputDecoration(
hintText: 'a hint text',
),
child: TextField(
onChanged: (v) => setState(() => _value = v),
),
),
CodePudding user response:
Probably, you should use decoration property of your TextField. Something like that:
SizedBox(
height: 50,
width: 100,
child: TextField(
decoration: InputDecoration(
border: OutlineInputBorder(),
label: Text('Your stable hint')
),
)
),