flutterdartanimationflutter-animationcustom-painting

Flutter: How to Create a Top-to-Bottom Animation Effect?


I'm working with Flutter and I aim to create an animation that transitions from the top to the bottom of the screen, similar to a fill effect. I've attached a GIF of the desired effect and what I currently have.

Desired effect:

View

Current effect:

gif

Here's the code snippet for my current implementation:

import 'dart:ui' as ui;

import 'package:flutter/material.dart';

class CustomTimePainter extends CustomPainter {
  CustomTimePainter({
    required this.animation,
    required this.backgroundColor,
    required this.color,
  }) : super(repaint: animation);

  final Animation<double> animation;
  final Color backgroundColor, color;

  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()..color = backgroundColor;
    canvas.drawPaint(paint);

    final top = ui.lerpDouble(0, size.height, animation.value)!;
    Rect rect = Rect.fromLTRB(0, 0, size.width, top);
    Path path = Path()..addRect(rect);

    canvas.drawPath(path, paint..color = color);
  }

  @override
  bool shouldRepaint(CustomTimePainter old) {
    return animation.value != old.animation.value ||
        color != old.color ||
        backgroundColor != old.backgroundColor;
  }
}

I expect the animation to fill the screen from top to bottom, but instead, it does the opposite. I've tried adjusting the lerpDouble parameters without success. Any suggestions on how I can achieve the top-to-bottom animation effect as shown in the first GIF?

Thanks for any help you can provide.


Solution

  • Switch your rect

    From

     Rect rect = Rect.fromLTRB(0, 0, size.width, top);
    

    To

    Rect rect = Rect.fromLTRB(0, top, size.width, size.height);
    

    This way bottom will be always size.height.

    More about Rect.fromLTRB