简体   繁体   English

如何在 Flutter 中向 TextFormField 添加静态单元(文本)?

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

I currently have this TextFormField with a hintText:我目前有一个带有hintText的TextFormField

当前文本表单字段

the goal is to add Units inside the TextFormField, regardless of whether the user is typing or not.目标是在 TextFormField 中添加 Units,无论用户是否正在输入。 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 代码:

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修饰可以是一个suffixText属性

     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文本可以使用textAlign属性居中

One way is to use TextFormField and text inside row which is inside a container something like this can help一种方法是在容器内的行内使用 TextFormField 和文本,这样可以帮助

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 时,您只会获得后缀文本,您可以尝试使其始终可见的一种解决方法是使用autovalidate属性,例如

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

I have not tested this autovalidateMode but it should work properly.我还没有测试过这个 autovalidateMode 但它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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