Monday, 16 June 2025

Flutter Fluid Fill Animation code

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider<AnimationData>(
      create: (context) => AnimationData(),
      builder: (context, child) => const MyApp(),
    ),
  );
}

class AnimationData extends ChangeNotifier {
  double _percentage = 0.0;
  bool _isAnimationRunning = false;

  double get percentage => _percentage;
  bool get isAnimationRunning => _isAnimationRunning;

  set percentage(double value) {
    _percentage = value;
    notifyListeners();
  }

  void startAnimation() {
    if (_isAnimationRunning) return;
    _isAnimationRunning = true;

    Timer.periodic(const Duration(milliseconds: 30), (timer) {
      if (_percentage < 1.0) {
        _percentage += 0.01;
        notifyListeners();
      } else {
        timer.cancel();
        _isAnimationRunning = false;
      }
    });
  }

  void resetAnimation() {
    _percentage = 0.0;
    notifyListeners();
  }
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fluid Fill Animation',
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<AnimationData>(context, listen: false).startAnimation();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Fluid Fill Animation')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const FluidCircle(),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () {
                    Provider.of<AnimationData>(
                      context,
                      listen: false,
                    ).startAnimation();
                  },
                  child: const Text('Start Animation'),
                ),
                const SizedBox(width: 20),
                ElevatedButton(
                  onPressed: () {
                    Provider.of<AnimationData>(
                      context,
                      listen: false,
                    ).resetAnimation();
                  },
                  child: const Text('Reset Animation'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

class FluidCircle extends StatelessWidget {
  const FluidCircle({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final animationData = Provider.of<AnimationData>(context);
    return CustomPaint(
      painter: FluidPainter(animationData.percentage),
      size: const Size(200, 200),
    );
  }
}

class FluidPainter extends CustomPainter {
  final double percentage;

  FluidPainter(this.percentage);

  @override
  void paint(Canvas canvas, Size size) {
    final center = size.center(Offset.zero);
    final radius = size.width / 2;

    // Define the wave parameters
    final waveAmplitude = radius / 20;
    final waveFrequency = 5.0;

    // Calculate the current water level
    final waterLevel = radius - (radius * 2 * percentage);

    // Create the path for the filled portion with wave effect
    final filledPath = Path();

    // Move to the starting point on the left, start from above the circle to avoid unfilled area
    filledPath.moveTo(0, center.dy + waterLevel - waveAmplitude);

    // Draw the wave
    for (double x = 0; x <= size.width; x += 1) {
      final y =
          center.dy +
          waterLevel +
          waveAmplitude *
              sin(waveFrequency * (x / radius) + percentage * 2 * pi);
      filledPath.lineTo(x, y);
    }

    // Complete the path to close the filled area
    filledPath.lineTo(size.width, size.height);
    filledPath.lineTo(0, size.height);
    filledPath.close();

    // Clip the path to the circle
    canvas.clipPath(
      Path()..addOval(Rect.fromCircle(center: center, radius: radius)),
    );

    // Draw the filled portion
    final filledPaint = Paint()..color = Colors.blue;
    canvas.drawPath(filledPath, filledPaint);

    // Draw the circle outline
    final circlePaint = Paint()
      ..color = Colors.blue
      ..style = PaintingStyle.stroke
      ..strokeWidth = 4;
    canvas.drawCircle(center, radius, circlePaint);

    // Draw the percentage text
    final textPainter = TextPainter(
      text: TextSpan(
        text: '${(percentage * 100).toStringAsFixed(0)}%',
        style: TextStyle(
          color: (percentage * 100) > 50 ? Colors.white : Colors.grey,
          fontSize: 24,
        ),
      ),
      textDirection: TextDirection.ltr,
      textAlign: TextAlign.center,
    );
    textPainter.layout(minWidth: size.width, maxWidth: size.width);
    textPainter.paint(
      canvas,
      center - Offset(textPainter.width / 2, textPainter.height / 2),
    );
  }

  @override
  bool shouldRepaint(covariant FluidPainter oldDelegate) {
    return oldDelegate.percentage != percentage;
  }
}



No comments:

Post a Comment