【问题标题】:How to set a height to a TextField?如何为 TextField 设置高度?
【发布时间】:2020-06-15 12:57:06
【问题描述】:

我正在尝试创建一个 40 像素高的 TextField,并以圆角矩形作为背景。不敢相信似乎没有一种直接的方法可以做到这一点。

这是我尝试过的:

  • Container 父级中设置高度。不起作用,孩子将自己画在父母的边界上。
  • 设置expands: true,这需要maxLines: null。请参阅下面的代码。这可行,但我想将行数限制为 1。
Container(
  decoration: BoxDecoration(
    color: Color(0xfff0f0f0),
    borderRadius: BorderRadius.circular(5),
  ),
  height: 40,
  child: TextField(
    style: TextStyle(fontSize: 18),
    expands: true,
    maxLines: null,
    decoration: InputDecoration(
      contentPadding:
          EdgeInsets.all(8),
      border: InputBorder.none,
      isDense: true,
    ),
  ))

【问题讨论】:

  • 你试过设置minLines: 1,吗?
  • 如果expands: true,则必须为null
  • 尝试使用sizedBox,它会强制调整其子项的大小。 api.flutter.dev/flutter/widgets/SizedBox-class.html
  • 也不起作用。我找到了解决方法,请参阅我的答案。

标签: flutter


【解决方案1】:

刚刚找到一个解决方法,像这样设置垂直填充:

contentPadding: EdgeInsets.symmetric(vertical: 9)

要找到具体值(本例中为 9),从 0 开始慢慢增加,热重载并观察文本向下移动。在某些时候,文本开始向上移动。选择使文本尽可能低的垂直填充。

【讨论】:

    【解决方案2】:

    我试过了,效果很好。

    Row(children: [ Flexible(flex:2,
        child:
          Container(
           margin: EdgeInsets.symmetric(horizontal: 15),
      decoration: BoxDecoration(
        color: Color(0xfff0f0f0),
        borderRadius: BorderRadius.circular(5),
      ),
      height: 40,
      child:  TextField(
        style: TextStyle(fontSize: 18),
    
        maxLines: 1,
        decoration: InputDecoration(
          contentPadding:
              EdgeInsets.all(8),
          border: InputBorder.none,
          isDense: true,
        ),
      )))])
    

    【讨论】:

      【解决方案3】:
      Wrap Your `Textfield` with `SizeBox` Widget and set height according to your design like below
      
      SizedBox(
          height: 45,
          child: TextField(
            autocorrect: autocorrect,
            enabled: enabled,
            readOnly: readOnly,
            textCapitalization: textCapitalization,
            onEditingComplete: onEditingComplete,
            obscureText: obscure,
            controller: controller,
            keyboardType: keyboardType,
            style: AppTheme.textFieldTextStyle(),
            decoration: InputDecoration(
              filled: true,
              contentPadding: textFieldPadding(),
              prefixIcon: perfixIcon,
              hintText: hint,
              fillColor: Colors.white,
              hintStyle: AppTheme.textFieldHintTextStyle()
                  .copyWith(fontWeight: FontWeight.w600),
            ),
            inputFormatters: [LengthLimitingTextInputFormatter(maxLength)],
            onTap: onTap,
            onSubmitted: onSubmit,
          ),
        );
      

      【讨论】:

        猜你喜欢
        • 2019-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多