问题描述
我想在 Flutter 中为 TextFormField
创建自定义基线。下面给出了我想要做的示例。
解决方法
您可以创建可以扩展 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,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
,第一个值得关注的地方是 UnderlineInputBorder 类。您应该能够将 decoration:
的 TextFormField
设置为 InputDecoration
,它可以将 UnderlineInputBorder
作为其 border:
。然后,您应该能够适当地设置边框的“BorderSide”属性样式以匹配您的设计。