Blast Colorful Confetti All Over The Screen For Flutter

Demo

Video showing the Confetti in Action: https://youtu.be/dGMVyUY4-6M

Live WEB Demo

An old video walkthrough is available here.

Getting Started

To use this plugin, add confetti as a dependency in your pubspec.yaml file.

See the example to get started quickly. To generate the platform folders run:

flutter create .

in the example folder.

To begin you need to instantiate a ConfettiController variable and pass in a Duration argument. The ConfettiController can be instantiated in the initState method and disposed in the dispose method.

In the build method return a ConfettiWidget. The only attribute that is required is the ConfettiController.

Other attributes that can be set are:

  • blastDirectionality -> an enum value to state if the particles shoot in random directions or a specific direction. BlastDirectionality.explosive will shoot in random directions and don't require a blastDirection to be set. BlastDirectionality.directional requires a blastDirection to specify the direction of the confetti.
  • blastDirection -> a radial value to determine the direction of the particle emission. The default is set to PI (180 degrees). A value of PI will emit to the left of the canvas/screen.
  • emissionFrequency -> should be a value between 0 and 1. The higher the value the higher the likelihood that particles will be emitted on a single frame. Default is set to 0.02 (2% chance)
  • numberOfParticles -> the number of particles to be emitted per emission. Default is set to 10
  • shouldLoop -> determines if the emission will reset after the duration is completed, which will result in continues particles being emitted, and the animation looping
  • maxBlastForce -> will determine the maximum blast force applied to a particle within it's first 5 frames of life. The default maxBlastForce is set to 20
  • minBlastForce -> will determine the minimum blast force applied to a particle within it's first 5 frames of life. The default minBlastForce is set to 5
  • displayTarget -> if true a crosshair will be displayed to show the location of the particle emitter
  • colors -> a list of colors can be provided to manually set the confetti colors. If omitted then random colors will be used. A single color, for example [Colors.blue], or multiple colors [Colors.blue, Colors.red, Colors.green] can be provided as an argument in the `ConfettiWidget
  • strokeWidth optionally set to give a stroke to the paint. Needs to be bigger than 0 to be vissible. Default 0.
  • strokeColor optionally set to give a stroke color. Default black.
  • minimumSize -> a Size controlling the minimum possible size of the confetti. To be used in conjuction with maximumSize. For example, setting a minimumSize equal to Size(10,10) will ensure that the confetti will never be smaller than the specified size. Must be positive and smaller than the maximumSize. Can not be null.
  • maximumSize -> a Size controlling the maximum possible size of the confetti. To be used in conjuction with minimumSize. For example, setting a maximumSize equal to Size(100,100) will create confetti with a size somewhere between the minimum and maximum size of (100, 100) [widht, height]. Must be positive and bigger than the minimumSize, Can not be null.
  • gravity -> change the speed at which the confetti falls. A value between 0 and 1. The higher the value the faster it will fall. Default is set to 0.1
  • particleDrag -> configure the drag force to apply to the confetti. A value between 0 and 1. A value of 1 will be no drag at all, while 0.1, for example, will be a lot of drag. Default is set to 0.05
  • canvas -> set the size of the area where the confetti will be shown, by default this is set to full screen size.
  • createParticlePath -> An optional function that retuns a custom Path to generate unique particles. Default returns a rectangular path.

Example of a custom createParticlePath

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;
  }

Enjoy the confetti.

NOTE: Don't be greedy with the number of particles. The more particles that are on screen the more calculations need to be performed. Performance improvements have been made, however this is still ongoing work. Too many particles will result in performance issues. Use wisely and carefully.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add confetti

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  confetti: ^0.7.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:confetti/confetti.dart';

example/lib/main.dart

import 'dart:math';

import 'package:confetti/confetti.dart';
import 'package:flutter/material.dart';

void main() => runApp(const ConfettiSample());

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Confetti',
        home: Scaffold(
          backgroundColor: Colors.grey[900],
          body: MyApp(),
        ));
  }
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late ConfettiController _controllerCenter;
  late ConfettiController _controllerCenterRight;
  late ConfettiController _controllerCenterLeft;
  late ConfettiController _controllerTopCenter;
  late ConfettiController _controllerBottomCenter;

  @override
  void initState() {
    super.initState();
    _controllerCenter =
        ConfettiController(duration: const Duration(seconds: 10));
    _controllerCenterRight =
        ConfettiController(duration: const Duration(seconds: 10));
    _controllerCenterLeft =
        ConfettiController(duration: const Duration(seconds: 10));
    _controllerTopCenter =
        ConfettiController(duration: const Duration(seconds: 10));
    _controllerBottomCenter =
        ConfettiController(duration: const Duration(seconds: 10));
  }

  @override
  void dispose() {
    _controllerCenter.dispose();
    _controllerCenterRight.dispose();
    _controllerCenterLeft.dispose();
    _controllerTopCenter.dispose();
    _controllerBottomCenter.dispose();
    super.dispose();
  }

  /// A custom Path to paint stars.
  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;
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Stack(
        children: <Widget>[
          //CENTER -- Blast
          Align(
            alignment: Alignment.center,
            child: ConfettiWidget(
              confettiController: _controllerCenter,
              blastDirectionality: BlastDirectionality
                  .explosive, // don't specify a direction, blast randomly
              shouldLoop:
                  true, // start again as soon as the animation is finished
              colors: const [
                Colors.green,
                Colors.blue,
                Colors.pink,
                Colors.orange,
                Colors.purple
              ], // manually specify the colors to be used
              createParticlePath: drawStar, // define a custom shape/path.
            ),
          ),
          Align(
            alignment: Alignment.center,
            child: TextButton(
                onPressed: () {
                  _controllerCenter.play();
                },
                child: _display('blast\nstars')),
          ),

          //CENTER RIGHT -- Emit left
          Align(
            alignment: Alignment.centerRight,
            child: ConfettiWidget(
              confettiController: _controllerCenterRight,
              blastDirection: pi, // radial value - LEFT
              particleDrag: 0.05, // apply drag to the confetti
              emissionFrequency: 0.05, // how often it should emit
              numberOfParticles: 20, // number of particles to emit
              gravity: 0.05, // gravity - or fall speed
              shouldLoop: false,
              colors: const [
                Colors.green,
                Colors.blue,
                Colors.pink
              ], // manually specify the colors to be used
              strokeWidth: 1,
              strokeColor: Colors.white,
            ),
          ),
          Align(
            alignment: Alignment.centerRight,
            child: TextButton(
                onPressed: () {
                  _controllerCenterRight.play();
                },
                child: _display('pump left')),
          ),

          //CENTER LEFT - Emit right
          Align(
            alignment: Alignment.centerLeft,
            child: ConfettiWidget(
              confettiController: _controllerCenterLeft,
              blastDirection: 0, // radial value - RIGHT
              emissionFrequency: 0.6,
              minimumSize: const Size(10,
                  10), // set the minimum potential size for the confetti (width, height)
              maximumSize: const Size(50,
                  50), // set the maximum potential size for the confetti (width, height)
              numberOfParticles: 1,
              gravity: 0.1,
            ),
          ),
          Align(
            alignment: Alignment.centerLeft,
            child: TextButton(
                onPressed: () {
                  _controllerCenterLeft.play();
                },
                child: _display('singles')),
          ),

          //TOP CENTER - shoot down
          Align(
            alignment: Alignment.topCenter,
            child: ConfettiWidget(
              confettiController: _controllerTopCenter,
              blastDirection: pi / 2,
              maxBlastForce: 5, // set a lower max blast force
              minBlastForce: 2, // set a lower min blast force
              emissionFrequency: 0.05,
              numberOfParticles: 50, // a lot of particles at once
              gravity: 1,
            ),
          ),
          Align(
            alignment: Alignment.topCenter,
            child: TextButton(
                onPressed: () {
                  _controllerTopCenter.play();
                },
                child: _display('goliath')),
          ),
          //BOTTOM CENTER
          Align(
            alignment: Alignment.bottomCenter,
            child: ConfettiWidget(
              confettiController: _controllerBottomCenter,
              blastDirection: -pi / 2,
              emissionFrequency: 0.01,
              numberOfParticles: 20,
              maxBlastForce: 100,
              minBlastForce: 80,
              gravity: 0.3,
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: TextButton(
                onPressed: () {
                  _controllerBottomCenter.play();
                },
                child: _display('hard and infrequent')),
          ),
        ],
      ),
    );
  }

  Text _display(String text) {
    return Text(
      text,
      style: const TextStyle(color: Colors.white, fontSize: 20),
    );
  }
}

Download details:

Author: funwith.app

Source: https://github.com/funwithflutter/flutter_confetti

#flutter #android #ios #web-development #ui 

Blast Colorful Confetti All Over The Screen For Flutter
1.70 GEEK