Search code examples
flutterflutter-layoutbaselinetextformfield

How to make custom baseline for `TextFormField` in Flutter


I want to create a custom baseline for TextFormField in Flutter. The example for what I wanna do is given below.

enter image description here


Solution

  • You can create your custom input border which would extend UnderlineInputBorder. What you need to override is the paint method. I implemented here in this manner so that you can easily add colors and it would then draw lines for you giving same width to each color, but feel free to update it for your needs. That would be something like this:

    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);
      }
    }
    

    And then you can use it:

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

    This is how it looks like right now:

    https://i.sstatic.net/fDTBu.png

    https://i.sstatic.net/z4SjM.png

    https://i.sstatic.net/l5aW8.png