How To Detect When An Animation Has Ended In Flutter App

admin_img Posted By Bajarangi soft , Posted On 06-11-2020

In this Google flutter code example we are going to learn how to detect when an animation has ended in Flutter.You can copy and adopt this source code example to your android project without reinventing the wheel.

How To Detect When An Animation Has Ended In Flutter App

Detect End Of An Animation
Complete Code For Detect End Of An Animation In Flutter
main.dart

import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  AnimationController animationController;
  Animation<double> animation;
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  void initState() {
    super.initState();
    animationController = AnimationController(
      vsync: this,
      duration: Duration(seconds: 5),
    )
      ..addListener(() => setState(() {}));

    animation = Tween<double>(
      begin: 50.0,
      end: 120.0,
    ).animate(animationController);

    animationController.forward();

    animation.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        scaffoldKey.currentState.showSnackBar(SnackBar(
          content: Text("Animation has ended"),
        ));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      appBar: AppBar(
        backgroundColor: Colors.cyan,
          title: Text("Detect End Of An Animation"
          )),
      body: Center(
        child: Container(
          color: Colors.cyan,
          height: animation.value,
          width: animation.value,
        ),
      ),
    );
  }
}

Related Post