How to add a static unit (text) to a TextFormField in Flutter?

Viewed 1616

I currently have this TextFormField with a hintText:

Current TextFormField

the goal is to add Units inside the TextFormField, regardless of whether the user is typing or not. It should kinda look like this:

goal

How to achieve this? Also, how to center the value?

Here's my current code for the TextFormField:

TextFormField(
  decoration: InputDecoration(
    hintText: '0.0',
    contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 5.0),
    filled: true,
    fillColor: Colors.white24,
    floatingLabelBehavior: FloatingLabelBehavior.never,
    border: OutlineInputBorder(
      borderRadius: BorderRadius.circular(10.0),
      borderSide: BorderSide.none,
    ),
    counterText: '',
  ),
),
2 Answers

TheTextFormField decoration can a suffixText property

     TextFormField(
       controller: c,
       // align to center
       textAlign: TextAlign.center,
       decoration:  InputDecoration(
         hintText: '0.0',
         // show kg
         suffixText: 'Kg',
     )

Text can be centered using the textAlign property

One way is to use TextFormField and text inside row which is inside a container something like this can help

Container(
          child: Row(
            children: [TextFormField(), Text('Kg')],
          ),
        ),

another way is that you can use

TextFormField(
                decoration: InputDecoration(suffixText: 'Kg'),
              ),

but here the problem is that you will only get suffix text when the TextFormField is enabled, one workaround you can try to make it always visible is to use autovalidate property like

TextFormField(
                autovalidateMode: AutovalidateMode.always,
                decoration: InputDecoration(suffixText: 'Kg'),
              ),

I have not tested this autovalidateMode but it should work properly.

Related