如何在 Flutter 中为 TextFormField 创建自定义基线

How to make custom baseline for `TextFormField` in Flutter

我想在 Flutter 中为 TextFormField 创建自定义基线。下面给出了我想做的示例。

首先值得一看的地方是 UnderlineInputBorder class。您应该能够将 TextFormFielddecoration: 设置为 InputDecoration,它可以将 UnderlineInputBorder 作为其 border:。然后,您应该能够适当地设置边框的“BorderSide”属性 样式以匹配您的设计。

您可以创建扩展 UnderlineInputBorder 的自定义输入边框。您需要覆盖的是 paint 方法。 我在这里以这种方式实现,以便您可以轻松添加颜色,然后它会为您绘制线条,为每种颜色提供相同的宽度,但您可以根据需要随意更新它。 那将是这样的:

class CustomInputBorder extends UnderlineInputBorder {
  @override
  void paint(Canvas canvas, Rect rect,
      {double gapStart,
      double gapExtent = 0.0,
      double gapPercentage = 0.0,
      TextDirection textDirection}) {
    drawLines(
        canvas, rect, [Colors.red, Colors.green, Colors.blue, Colors.orange]);
  }

  void drawLines(Canvas canvas, Rect rect, List<Color> colors) {
    var borderWidth = rect.bottomRight.dx - rect.bottomLeft.dx;
    var sectionWidth = borderWidth / colors.length;
    var startingPoint = rect.bottomLeft;
    var endPoint = getEndPoint(startingPoint, sectionWidth);

    colors.forEach((color) {
      var paint = Paint();
      paint.color = color;
      paint.strokeWidth = 1.0;

      canvas.drawLine(startingPoint, endPoint, paint);

      startingPoint = getNewStartingPoint(startingPoint, sectionWidth);
      endPoint = getEndPoint(startingPoint, sectionWidth);
    });
  }

  Offset getNewStartingPoint(Offset oldStartingPoint, double width) {
    return Offset(oldStartingPoint.dx + width, oldStartingPoint.dy);
  }

  Offset getEndPoint(Offset startingPoint, double width) {
    return Offset(startingPoint.dx + width, startingPoint.dy);
  }
}

然后就可以使用了:

TextField(
  decoration: InputDecoration(
    labelText: 'Username',
    border: CustomInputBorder(),
    enabledBorder: CustomInputBorder(),
    focusedBorder: CustomInputBorder(),
  ),
),

这是现在的样子:

https://i.stack.imgur.com/fDTBu.png

https://i.stack.imgur.com/z4SjM.png

https://i.stack.imgur.com/l5aW8.png