How to draw horizontal line in a Flutter?

One of the exciting features it offers is the ability to draw horizontal line in flutter and create custom drawings and graphics. In this blog, we’ll explore a simple example of Drawing a horizontal line and a vertical or any kind of line in Flutter.

To create a simple app that allows users to draw a horizontal line between two points, we’ll use Flutter CustomPainter and GestureDetector widgets. Let’s break down the code step by step.

import 'package:flutter/material.dart';

void main() => runApp(TestDraw2Point());

class TestDraw2Point extends StatefulWidget {
  @override
  _TestDraw2PointState createState() => _TestDraw2PointState();
}

class _TestDraw2PointState extends State<TestDraw2Point> {
  List<Offset> _points = [];

  void _addPoint(Offset point) {
    setState(() {
      _points.add(point);
      if (_points.length == 2) {
        _points = List.from(_points);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Draw Line Example'),
        ),
        body: GestureDetector(
          onTapDown: (TapDownDetails details) {
            _addPoint(details.localPosition);
          },
          child: CustomPaint(
            painter: LinePainter(points: _points),
            child: Container(),
          ),
        ),
      ),
    );
  }
}

class LinePainter extends CustomPainter {
  List<Offset> points;

  LinePainter({required this.points});

  @override
  void paint(Canvas canvas, Size size) {
    if (points.length == 2) {
      final paint = Paint()
        ..color = Colors.black
        ..strokeWidth = 3.0;

      canvas.drawLine(points[0], points[1], paint);
    }
  }

  @override
  bool shouldRepaint(LinePainter oldDelegate) => true;
}

Understanding the Code to Draw horizontal line in a flutter

if (points.length == 2): This condition checks whether there are exactly two points in the points list. This ensures that a line is drawn only when two distinct points are available.

final paint = Paint()..color = Colors.black..strokeWidth = 3.0;: Here, we create an Paint object to define the appearance of the line. The color property sets the line color to black and strokeWidth sets the width of the line to 3.0 pixels.

canvas.drawLine(points[0], points[1], paint);: Using the Canvas API, the drawLine method is called to draw a line between the first (points[0]) and second (points[1]) points in the points list. The paint object determines the visual attributes of the line, such as color and width.

1. The TestDraw2Point Widget

This widget serves as the main entry point for our application. It contains a Scaffold with an AppBar and a GestureDetector wrapped around a CustomPaint widget.

2. TestDraw2PointState Class

This is the state class for our TestDraw2Point widget. It maintains a list of Offset points, representing the touch points where the user taps on the screen. The _addPoint method is called when the user taps, adding the local position of the tap to the list.

3. LinePainter CustomPainter

The LinePainter class is responsible for painting the line between two points. It extends CustomPainter and overrides the paint method to draw the line using the Canvas API.

The shouldRepaint method always returns true, indicating that the painter should be repainted when the widget is rebuilt.

Additional Information:

  • Canvas: In Flutter, the Canvas class is a 2D drawing context that allows you to draw on the screen. It provides methods for drawing lines, shapes, text, and images.
  • Paint: The Paint class defines how to paint on a canvas. It includes properties like color, stroke width, style, and more.
  • drawLine: This method draws a line between two points on the canvas. It takes the starting and ending points of the line as arguments, along with an Paint object that specifies the line’s appearance.

By customizing the properties of the Paint object or modifying the drawing logic within the paint method, you can achieve various visual effects and styles when drawing lines in Flutter.

Running the App

To run the app, use your preferred Flutter development environment, such as VS Code or Android Studio. Make sure you have Flutter and Dart installed on your machine. Then, connect a device or use an emulator and run:

flutter run

This will launch the app, allowing you to tap on the screen and draw lines between two points.

Outputs:

Drawing lines in Flutter is straightforward with the combination of CustomPainter user gestures.

Conclusion

Drawing lines in Flutter is straightforward with the combination of CustomPainter user gestures. This example provides a foundation for more complex drawing functionalities, making Flutter versatile for creating interactive and visually appealing applications.

Feel free to extend and modify the code to suit your specific requirements and explore the possibilities of Flutter’s rich set of features.

Share:

Ambika Dulal is a Flutter developer from Nepal who is passionate about building beautiful and user-friendly apps. She is always looking for new challenges and is eager to learn new things. She is also a strong believer in giving back to the community and is always willing to help others.

Leave a Comment

AO Logo

App Override is a leading mobile app development company based in Kathmandu, Nepal. Specializing in both Android and iOS app development, the company has established a strong reputation for delivering high-quality and innovative mobile solutions to clients across a range of industries.

Services

UI/UX Design

Custom App Development

Mobile Strategy Consulting

App Testing and Quality Assurance

App Maintenance and Support

App Marketing and Promotion

Contact

App Override

New Plaza, Kathmandu