【问题标题】:Flutter - setting width to a TextFormFieldFlutter - 将宽度设置为 TextFormField
【发布时间】:2020-07-12 15:50:36
【问题描述】:

如果我想要一个具有特定宽度的 TextFormField - 比如说 70 像素中的一个小像素 - 我需要将它包装在一个具有“宽度”属性的容器中。但是如果我这样做,错误文本(以防字段未通过验证)也将被限制在这个固定宽度的容器中。即使我使字段本身变窄,我也想让错误文本遍布整个屏幕宽度。可能吗? TextFormField 是否具有某种“宽度”属性,或者有人知道解决方法吗?感觉这是一个非常基本的要求。

Container(
  width: 70,
  child: TextFormField(
    ...
    decoration: // Just a custom input decoration...
    validator: (value) {
      if (value.length != 3) {
        return '3 digits required.';
      }
      return null;
    },
  ),
);

【问题讨论】:

    标签: flutter flutter-layout


    【解决方案1】:

    您可以在单独的全宽容器中显示自己的错误文本。

    首先在State类中存储一个新变量。

    String _errorMessage = null;
    

    并在您的渲染方法中更新验证器内的值,并将值传递给 if 条件以显示/隐藏错误消息。

    Column(
      children: <Widget>[
        SizedBox(
          width: 70,
          child: TextFormField(
            decoration: InputDecoration(
              errorStyle: TextStyle(height: 0),
            ),
            validator: (value) {
              String setError(String msg) {
                if (_errorMessage != msg) {
                  setState(() { _errorMessage = msg; });
                }
                return msg;
              }
    
              if (value.length != 3) {
                return setError('3 digits required.');
              }
    
              return setError(null);
            },
          ),
        ),
        if (_errorMessage != null)
        Text(_errorMessage, style: TextStyle(
          color: Colors.red,
        )),
      ],
    ),
    

    【讨论】:

      【解决方案2】:

      如果您想更改TextFormField 的宽度,请使用SizedBox()。如果您想在整个屏幕上传播错误消息,请使用 Column()TextFormField()Text() 小部件。你可以使用

      Container( 
      width: 100
      height: 20
      child:
          FittedBox(
              fit: BoxFit.contain,
              child: Text('test text'),
          )
      )
      

      相对于其父 Widget 调整文本大小。

      【讨论】:

      • 代码示例不包含 TextFormField
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 2019-07-16
      相关资源
      最近更新 更多