Flutter and Sprite Widget

Aseem Wangoo
Jan 20 · 4 min read

Life is an experiment!!!!


All in one Flutter Resource:

Flutter and Sprite Widget

Fluttering through the widget world of Flutter, I stuck upon an interesting use case. We often see the weather updates may be in our phones, desktops etc, but we do….

I questioned myself, how to implement the stylish raining background or scorching heat one….Hmmm!!!!

Begin…

Introducing Sprite Widget,

As per the documentation,

SpriteWidget is an open source toolkit for building complex, high performance animations and 2D games with Flutter. You can use SpriteWidget to create anything from an animated icon to a full fledged game.

Whoa, that was all I needed…

Flutter and Sprite

Merging with Flutter :

  1. SpriteWidget is available like any other package. Just add it as a dependency to your pubspec.yaml and you are good to go.
dependencies:
  flutter:
    sdk: flutter
  spritewidget:

2. Import the following line

import 'package:spritewidget/spritewidget.dart';


Adding rain droplets :

  1. Initialize the ImageMap and SpriteSheet.
  2. Load images using the ImageMap and SpriteSheet, which contains rain drops.
  ImageMap _imageMap = new ImageMap(bundle);

  await _imageMap.load(<String>[
      'assets/icon-rain.png',
      'assets/weathersprites.png',
  ]);

String json = await DefaultAssetBundle.of(context)
        .loadString('assets/weathersprites.json');
    _sprites = new SpriteSheet(_imageMap['assets/weathersprites.png'], json);

3. Do step 1 and 2, in the initState of your Stateful Widget.

    _loadAssets(assetBundle).then((_) {
      setState(() {
        assetsLoaded = true;
        world = new RainWorld();
      });
    });

Definition of _loadAssets :

Future<Null> _loadAssets(AssetBundle bundle) async {}

4. We need to initialize the RainWorld(). What is RainWorld???

A root node that is used to draw it’s contents. Any sprite nodes that you add to the root node will be rendered by the SpriteWidget.

class RainWorld extends NodeWithSize {
  RainNode _rain;
  RainWorld() : super(const Size(2048.0, 2048.0)) {
    _rain = new RainNode();
    _rain.active = true;
    addChild(_rain);
  }
}

5. Finally we need to setup our RainNode(). What is RainNode???

A base class for all objects that can be added to the sprite node tree and rendered to screen using SpriteBox and SpriteWidget.

The Node class itself doesn't render any content, but provides the basic functions of any type of node, such as handling transformations and user input. To render the node tree, a root node must be added to a SpriteBox or a SpriteWidget. Commonly used sub-classes of Node are Sprite, NodeWithSize etc.

class RainNode extends Node {
}

Final look of RainNode,

RainNode

In the _addParticles, we simply take up the parameters as provided by the SpriteWidget class and manipulate by the input parameter(distance).

Note : ParticleSystem is a part of SpriteWidget package. We are not creating anything new.

 void _addParticles(double distance) {
    ParticleSystem particleSystem = ParticleSystem(
      _sprites['raindrop.png'],
      transferMode: BlendMode.srcATop, //lighten
      posVar: const Offset(1300.0, 0.0),
      direction: 90.0,
      directionVar: 0.0,
      speed: 10000.0 / distance,
      speedVar: 100.0 / distance,
      startSize: 1.2 / distance,
      startSizeVar: 0.2 / distance,
      endSize: 1.2 / distance,
      endSizeVar: 0.2 / distance,
      life: 1.5 * distance,
      lifeVar: 1.0 * distance,
      maxParticles: 15,
    );

    particleSystem.position = const Offset(1024.0, -200.0);
    particleSystem.rotation = 10.0;
    particleSystem.opacity = 0.0;

    _particles.add(particleSystem);
    addChild(particleSystem);
  }

Feel free to tweak, the above values according to you…

Lastly, add the animations to the particles

set active(bool active) {
    actions.stopAll();
    for (ParticleSystem system in _particles) {
      if (active) {
        actions.run(new ActionTween<double>(
          (a) => system.opacity = a,
          system.opacity,
          1.0,
          2.0,
        ));
      } else {
        actions.run(new ActionTween<double>(
            (a) => system.opacity = a, system.opacity, 0.0, 0.5));
      }
    }
  }

ActionTween (from SpriteWidget)

Creates a new tween action. The setter will be called to update the animated property from startVal to endVal over the duration time in seconds. Optionally an animation curve can be passed in for easing the animation.

Phew…..We are ready

For complete source code :


The is a medium publication to bring you the latest and amazing resources such as articles, videos, codes, podcasts etc. about this great technology to teach you how to build beautiful apps with it. You can find us on , , and or learn more about us . We’d love to connect! And if you are a writer interested in writing for us, then you can do so .

FlutterPub

The Pub(lication) for all about the Flutter and its magic

Aseem Wangoo

Written by

Mobile Application Developer | Founder of Flatteredwithflutter.com | Flutter, Java enthusiast | Medium writer | YouTuber | Writer at FlutterPub

FlutterPub

The Pub(lication) for all about the Flutter and its magic