Open In App

Flutter – Display a Line Being Drawn from One Point to Another

Last Updated : 26 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

A line animation in Flutter could involve drawing and animating lines on the screen. To implement this in Flutter, we can use the Flutter custom painting to draw this. In this article, we are going to draw a line using a custom painting class and then add some animated motion to it like the effect of a line moving horizontally across the screen. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(
    MyApp(),
  );
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp and the Scaffold , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('Line Animation Example'), // App bar title
        ),
        body: LineAnimationView(), 
      ),
    );
  }
}


Step 5: Create LineAnimationView Class

The LineAnimationView class sets up and controls an animation of a line using an AnimationController and a CustomPainter(LinePainter).Comments are added for better understanding.

Dart




class LineAnimationView extends StatefulWidget {
  @override
  _LineAnimationViewState createState() => _LineAnimationViewState();
}
  
class _LineAnimationViewState extends State<LineAnimationView>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this, // Synchronize animation with this widget
      duration: Duration(seconds: 2), // Animation duration
    )..repeat(reverse: true); // Repeat the animation back and forth
  }
  
  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return CustomPaint(
          size: Size(
            MediaQuery.of(context).size.width,
            100.0,
          ),
          painter: LinePainter(
              _controller.value), // Use LinePainter to draw the line
        );
      },
    );
  }
  
  @override
  void dispose() {
    _controller.dispose(); // Dispose of the animation controller
    super.dispose();
  }
}


Step 6: Create LinePainter Class

The LinePainter class is responsible for painting a line on the canvas, and the position of the line is controlled by the animationValue. This class is used in conjunction with an animation controller to create the effect of a line moving horizontally across the screen as part of an animation.

Dart




class LinePainter extends CustomPainter {
  final double animationValue; // Animation value to control line position
  
  LinePainter(this.animationValue);
  
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.green // Line color
      ..style = PaintingStyle.stroke // Stroke style
      ..strokeWidth = 5.0; // Stroke width
  
    final double startX = 0;
    final double endX = size.width;
    final double y = size.height / 2;
  
    final double currentX = startX + (endX - startX) * animationValue;
  
    // Draw the line
    canvas.drawLine(Offset(startX, y), Offset(currentX, y), paint);
  }
  
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true; // Repaint the line continuously
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(
    MyApp(),
  );
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(
          title: Text('Line Animation Example'), // App bar title
        ),
        body: LineAnimationView(), 
      ),
    );
  }
}
  
class LinePainter extends CustomPainter {
  final double animationValue; // Animation value to control line position
  
  LinePainter(this.animationValue);
  
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.green // Line color
      ..style = PaintingStyle.stroke // Stroke style
      ..strokeWidth = 5.0; // Stroke width
  
    final double startX = 0;
    final double endX = size.width;
    final double y = size.height / 2;
  
    final double currentX = startX + (endX - startX) * animationValue;
  
    // Draw the line
    canvas.drawLine(Offset(startX, y), Offset(currentX, y), paint);
  }
  
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true; // Repaint the line continuously
  }
}
  
class LineAnimationView extends StatefulWidget {
  @override
  _LineAnimationViewState createState() => _LineAnimationViewState();
}
  
class _LineAnimationViewState extends State<LineAnimationView>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  
  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this, // Synchronize animation with this widget
      duration: Duration(seconds: 2), // Animation duration
    )..repeat(reverse: true); // Repeat the animation back and forth
  }
  
  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _controller,
      builder: (context, child) {
        return CustomPaint(
          size: Size(
            MediaQuery.of(context).size.width,
            100.0,
          ),
          painter: LinePainter(
              _controller.value), // Use LinePainter to draw the line
        );
      },
    );
  }
  
  @override
  void dispose() {
    _controller.dispose(); // Dispose of the animation controller
    super.dispose();
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads