为什么Flutter中的多行TextField有额外的垂直内边距?

问题描述 投票:0回答:1

我正在 Flutter 中实现具有动态高度的多行 TextField。 TextField 根据文本的高度调整大小。这是我的实现:

class MyTextField extends StatefulWidget {
  const MyTextField({
    super.key,
    this.controller,
    this.focusNode,
    this.text,
    this.placeholder,
    this.textColor,
    this.fontSize,
    this.isCompleted = false,
  });

  final TextEditingController? controller;
  final FocusNode? focusNode;
  final String? text;
  final String? placeholder;
  final Color? textColor;
  final double? fontSize;
  final bool isCompleted;

  @override
  State<MyTextField> createState() => _MyTextFieldState();
}

class _MyTextFieldState extends State<MyTextField> {
  void _onTextChanged(String text) {
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final textStyle = TextStyle(
          color: widget.textColor,
          fontSize: widget.fontSize,
          height: 24 / 16,
        );

        final painter = TextPainter(
          text: TextSpan(
            text: widget.controller?.text, 
            style: textStyle
          ),
          textDirection: Directionality.of(context),
        )..layout(maxWidth: constraints.maxWidth);

        return SizedBox(
          height: painter.height,
          child: TextField(
            controller: widget.controller,
            focusNode: widget.focusNode,
            onChanged: _onTextChanged,
            style: textStyle.copyWith(
              decoration: widget.isCompleted
                  ? TextDecoration.lineThrough
                  : TextDecoration.none,
            ),
            maxLines: null,
            expands: true,
            cursorColor: Theme.of(context).primaryColor,
            cursorHeight: 16,
            decoration: InputDecoration(
              contentPadding: EdgeInsets.zero,
              border: InputBorder.none,
              isDense: true,
              hintText: widget.placeholder,
              hintStyle: textStyle.copyWith(
                color: Colors.grey.shade400,
              ),
            ),
          ),
        );
      },
    );
  }
}

问题是 TextField 的高度按预期动态增加,但是当我按“Enter”添加换行符时,文本向上移动,并且 TextField 变得可滚动。

即使我将 contentPadding 设置为 EdgeInsets.zero,似乎还是有一些额外的垂直填充。

为什么会发生这种情况,如何去除多余的填充物?

flutter textfield multiline
1个回答
0
投票

将高度设置为TextField的样式,这控制行高。默认值为 1.0。您可以将其设置为较低的值(例如 1.2)以减少行之间的间距。

style: TextStyle(
        height: 1.2,
      ),
© www.soinside.com 2019 - 2024. All rights reserved.