Animated Background in Flutter
Animated Backgrounds for Flutter is easily extended to paint whatever you want on the canvas. In this article, we are going to make an animated background with bubbles. A sample video is given below to get an idea about what we are going to do in this article.
Installing
Add the dependency into pubspec.yaml file.
dependencies: animated_background: ^2.0.0
Syntax for usage
Creating ParticleOptions:
Dart
// Defining Particles for animation. ParticleOptions particles = const ParticleOptions( baseColor: Colors.cyan, spawnOpacity: 0.0, opacityChangeRate: 0.25, minOpacity: 0.1, maxOpacity: 0.4, particleCount: 70, spawnMaxRadius: 15.0, spawnMaxSpeed: 100.0, spawnMinSpeed: 30, spawnMinRadius: 7.0, ); |
Adding Widget to Body:
Dart
// AnimatedBackground widget AnimatedBackground( vsync: this , behaviour: RandomParticleBehaviour(options: particles), child: Center( child: Text( "Hello this is Random Animated Background" , style: TextStyle(fontSize: 50), )), ), |
Code Example
Dart
import 'package:animated_background/animated_background.dart' ; import 'package:flutter/material.dart' ; // main class calling to // the MyAnimatedBackground. void main() { runApp(MyAnimatedBackground()); } // MyAnimatedBackground class is stateful class. class MyAnimatedBackground extends StatefulWidget { MyAnimatedBackground({Key? key}) : super(key: key); @override State<MyAnimatedBackground> createState() => _MyAnimatedBackgroundState(); } class _MyAnimatedBackgroundState extends State<MyAnimatedBackground> with SingleTicketProviderStateMixin { // definition of ParticlesOptions. ParticleOptions particles = const ParticleOptions( baseColor: Colors.cyan, spawnOpacity: 0.0, opacityChangeRate: 0.25, minOpacity: 0.1, maxOpacity: 0.4, particleCount: 70, spawnMaxRadius: 15.0, spawnMaxSpeed: 100.0, spawnMinSpeed: 30, spawnMinRadius: 7.0, ); @override Widget build(BuildContext context) { // return MaterialApp return MaterialApp( debugShowCheckedModeBanner: false , home: Scaffold( appBar: AppBar( title: Text( "Animated Background" ), ), // In body we have a AnimatedBackgound, // behavior RandomParticleBehaviour. body: AnimatedBackground( // vsync uses singleTicketProvider state mixin. vsync: this , behaviour: RandomParticleBehaviour(options: particles), child: Center( child: Text( // center text "Hello this is Random Animated Background" , style: TextStyle(fontSize: 50), )), ), ), ); } } |
Explanation
- main is the principal method used to run the MyAnimatedBackground Class on start.
- Creating Class MyAnimatedBackground is a stateful widget.
- Creating ParticleOptions variable particles with options given.
- As flutter is based on widgets we need to create one.
- Returning MaterialApp that takes as home Scaffold that allows using body and appearance.
- As a body taking Animated Background that takes Behavior the particle that we have created,
- Vsync to play Animation and taking as a child Center.
- The Center has a Text Widget with text.
Contact Us