简体   繁体   中英

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

I currently have this TextFormField with a hintText:

当前文本表单字段

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

目标

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: '',
  ),
),

The TextFormField 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM