Flutter: How to animate a widget before transition is triggered?

1,261

You need to use AnimationController and configure it for your FAB and attach AnimationStatusListener. After FAB is pressed you start the animation and in your status listener once the animation completes you will navigate to a next page.

Here I wrote a code for you:

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

void main() => runApp(
      MaterialApp(
        home: FabApp(),
      ),
    );

class FabApp extends StatefulWidget {
  _FabAppState createState() => _FabAppState();
}

class _FabAppState extends State<FabApp> with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    );
    controller.addListener(() {
      setState(() {});
    });
    controller.addStatusListener((status) {
      if (status == AnimationStatus.completed) {
        Navigator.of(context).push(
          MaterialPageRoute<void>(builder: (BuildContext context) {
            return Scaffold(
              body: Text("Hi"),
            );
          }),
        );
      }
    });
    animation = Tween<double>(begin: 1, end: 0).animate(controller);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: Transform.scale(
        scale: animation.value,
        child: FloatingActionButton(onPressed: () {
          controller.forward();
        }),
      ),
    );
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
Share:
1,261
Jeremi
Author by

Jeremi

TechStack: PHP, Java, JavaScript and Android Dev as a hobby.

Updated on December 09, 2022

Comments

  • Jeremi
    Jeremi over 1 year

    Do you know how we could animate widgets before a transition to a new screen occurs? What I mean by that is:

    1. User clicks on FAB, which opens a new screen
    2. Right after the user click, FAB is animated to scale down until is invisible (just like hide function in native development)
    3. When FAB is invisible, new screen transition is triggered

    It's relatively easy to achieve this in native development with one activity/multiple fragments but I can't find a way to do this in flutter :/