flutter_confetti

repository·master·Indexed 19 days ago

https://github.com/funwithflutter/flutter_confetti

A Flutter plugin for creating customizable confetti animations to celebrate user achievements. It provides the ConfettiWidget for rendering and ConfettiController for managing the animation lifecycle. Key features include customizable particle shapes via createParticlePath, adjustable physics (gravity, blast force, and air resistance), and configurable emission patterns using BlastDirectionality.

Tokens
3.8K
Snippets
9
Records
15
Agent score
65%

What's inside flutter_confetti

  1. Implement the ConfettiWidget

    master

    To use the confetti effect, follow these steps:

    1. Instantiate a ConfettiController: Create a ConfettiController variable and pass in a Duration argument. It is recommended to instantiate this in your initState method and call dispose() in your dispose method to prevent memory leaks.
    2. Add the ConfettiWidget: In your build method, return a ConfettiWidget. The only required attribute is the ConfettiController.

    Note: Avoid using an excessive number of particles, as high particle counts can lead to performance issues.

    // Conceptual usage pattern
    late ConfettiController _controller;
    
    @override
    void initState() {
      _controller = ConfettiController(duration: const Duration(seconds: 2));
      super.initState();
    }
    
    @override
    void dispose() {
      _controller.dispose();
      super.dispose();
    }
    
    @override
    Widget build(BuildContext context) {
      return ConfettiWidget(controller: _controller);
    }
  2. How ParticleSystem status works

    master

    The ParticleSystemStatus enum manages the lifecycle of the confetti effect:

    1. started: The system is actively emitting new particles based on the emissionFrequency and updating existing ones.
    2. stopped: Emission of new particles ceases. Existing particles continue to move and update until they move outside the screen borders, at which point they are deactivated.
    3. finished: The system is no longer active, and all particles have been cleared.
  3. Create custom particle shapes with createParticlePath

    master

    You can generate unique particle shapes by providing a custom function to the createParticlePath attribute of the ConfettiWidget. This function should accept a Size and return a Path object.

    Below is an example of how to implement a star-shaped particle path:

    Path drawStar(Size size) {
        // Method to convert degree to radians
        double degToRad(double deg) => deg * (pi / 180.0);
    
        const numberOfPoints = 5;
        final halfWidth = size.width / 2;
        final externalRadius = halfWidth;
        final internalRadius = halfWidth / 2.5;
        final degreesPerStep = degToRad(360 / numberOfPoints);
        final halfDegreesPerStep = degreesPerStep / 2;
        final path = Path();
        final fullAngle = degToRad(360);
        path.moveTo(size.width, halfWidth);
    
        for (double step = 0; step < fullAngle; step += degreesPerStep) {
          path.lineTo(halfWidth + externalRadius * cos(step),
              halfWidth + externalRadius * sin(step));
          path.lineTo(halfWidth + internalRadius * cos(step + halfDegreesPerStep),
              halfWidth + internalRadius * sin(step + halfDegreesPerStep));
        }
        path.close();
        return path;
      }
  4. Configure ConfettiWidget attributes

    master

    The ConfettiWidget provides several attributes to customize the animation:

    AttributeTypeDescription
    blastDirectionalityBlastDirectionalityBlastDirectionality.explosive shoots in random directions. BlastDirectionality.directional requires blastDirection to be set.
    blastDirectiondoubleA radial value for emission direction. Default is PI (180 degrees, emitting to the left).
    emissionFrequencydoubleLikelihood of particles being emitted on a single frame (0 to 1). Default is 0.02.
    numberOfParticlesintNumber of particles per emission. Default is 10.
    shouldLoopboolIf true, the animation resets and loops after the duration completes.
    maxBlastForcedoubleMaximum blast force applied during the first 5 frames. Default is 20.
    minBlastForcedoubleMinimum blast force applied during the first 5 frames. Default is 5.
    displayTargetboolIf true, displays a crosshair showing the emitter location.
    colorsList<Color>Manually set confetti colors (e.g., [Colors.blue, Colors.red]). If omitted, colors are random.
    strokeWidthdoubleWidth of the paint stroke. Must be > 0 to be visible. Default is 0.
    strokeColorColorColor of the stroke. Default is black.
    minimumSizeSizeMinimum possible size of confetti. Must be positive and smaller than maximumSize.
    maximumSizeSizeMaximum possible size of confetti. Must be positive and larger than minimumSize.
    gravitydoubleSpeed at which confetti falls (0 to 1). Higher is faster. Default is 0.1.
    particleDragdoubleDrag force (0 to 1). 1 is no drag, 0.1 is high drag. Default is 0.05.
    canvasSizeThe size of the area where confetti is shown. Defaults to full screen.
    createParticlePathFunction(Size)Optional function returning a custom Path for unique particle shapes. Default is rectangular.
  5. Customize particle shapes with createParticlePath

    master

    By default, ConfettiWidget generates rectangular particles. You can provide a custom shape by passing a function to the createParticlePath parameter. This function receives the particle's Size and must return a Path object representing the shape of the confetti piece.

    ConfettiWidget(
      confettiController: controller,
      createParticlePath: (size) {
        return Path()..addCircle(Offset(size.width / 2, size.height / 2), size.width / 2);
      },
    )
  6. Update the ParticleSystem animation

    master

    The update(double deltaTime, {bool pauseEmission = false}) method must be called (typically within a ticker or animation loop) to advance the physics simulation.

    • deltaTime: The time elapsed since the last update.
    • pauseEmission: If true, the system will continue to update and move existing particles but will not generate new ones.
  7. Manage ParticleSystem position and screen size

    master

    To ensure particles are rendered correctly relative to the UI, you must update the ParticleSystem with the emitter's position and the screen dimensions:

    • particleSystemPosition: Set this Offset to define where the particles originate from.
    • screenSize: Set this Size to define the boundaries. This is used to calculate when particles have moved off-screen and can be deactivated/reused.
  8. Monitor ParticleSystem status and particle counts

    master

    Use these properties to track the state of your animation:

    • particleSystemStatus: Returns the current ParticleSystemStatus (started, finished, or stopped).
    • numberOfParticles: The total number of Particle objects currently managed in memory (active + inactive).
    • activeNumberOfParticles: The number of particles currently visible and animating on screen.
  9. Monitor particle statistics via particleStatsCallback

    master

    You can track the number of active particles in the system using the particleStatsCallback on the ConfettiController. This is useful for performance monitoring or syncing UI elements with the confetti density.

    final controller = ConfettiController(
      particleStatsCallback: (stats) {
        print('Active particles: ${stats.activeNumberOfParticles}');
      },
    );
  10. Use ConfettiWidget to display confetti

    master

    The ConfettiWidget is the primary UI component used to render confetti on the screen. It requires a ConfettiController to manage the animation lifecycle. You can wrap any existing widget with child to place the confetti on top of it, or use it as a standalone overlay.

    Key Configuration Options:

    • confettiController: (Required) The controller that triggers the animation.
    • emissionFrequency: Likelihood of particles being emitted per frame (0.0 to 1.0). Default is 0.02.
    • numberOfParticles: Number of particles emitted per burst. Default is 10.
    • maxBlastForce / minBlastForce: Determines the initial velocity of particles. maxBlastForce must be greater than minBlastForce.
    • gravity: Speed at which particles fall (0.0 to 1.0). Default is 0.1.
    • colors: A list of colors to use. If null, random colors are chosen.
    • blastDirectionality: Controls if particles follow a specific direction or are radial.
    • blastDirection: A radial value (in radians) determining the emission direction. pi (180°) emits to the left.
    • createParticlePath: An optional function to return a custom Path for particle shapes.
    • shouldLoop: If true, the animation resets upon completion for continuous emission.
    ConfettiWidget(
      confettiController: myController,
      blastDirectionality: BlastDirectionality.directional,
      blastDirection: pi,
      colors: [Colors.red, Colors.blue, Colors.green],
      child: MyWidget(),
    )
  11. Control ParticleSystem emission lifecycle

    master

    You can manually control the state of the ParticleSystem using the following methods:

    • startParticleEmission(): Sets the status to ParticleSystemStatus.started, allowing the system to begin emitting particles based on the configured frequency.
    • stopParticleEmission({bool clearAllParticles = false}): Sets the status to ParticleSystemStatus.stopped. If clearAllParticles is set to true, all currently active particles are immediately removed.
    • finishParticleEmission(): Sets the status to ParticleSystemStatus.finished and clears all particles from the system.