Flutter AnimatedSwitcher Examples

A simple AnimatedSwitcher Example in Flutter.

Example 1: AnimatedSwitcher

Here is the demo screenshot of this example:

Flutter AnimatedSwitcher

This example will comprise the following files:

  • AnimatedSwitcherExample.dart

Step 1: Create Project.

  1. Open your favorite Flutter IDE.
  2. Go to File-->New-->Project to create a new project.

Step 2: Dependencies.

No external dependencies are needed.

Step 4: Write Dart Code

Write your code as follows:

*(a). AnimatedSwitcherExample.dart

Create a file Dart named AnimatedSwitcherExample.dart

Here is the full code

import 'package:flutter/material.dart';
class AnimatedSwitcherExample extends StatefulWidget {
  const AnimatedSwitcherExample({Key? key, required this.title})
      : super(key: key);
  final String title;
  @override
  _AnimatedSwitcherExampleState createState() =>
      _AnimatedSwitcherExampleState();
}
class _AnimatedSwitcherExampleState extends State<AnimatedSwitcherExample> {
  int _counter = 0;
  void _incrementCounter() {
    setState(() {
      _counter += 1;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Column(
              children: <Widget>[
                const Text(
                  'You have pushed the button this many times:',
                ),
                AnimatedSwitcher(
                  duration: const Duration(milliseconds: 500),
                  transitionBuilder:
                      (Widget child, Animation<double> animation) {
                    return ScaleTransition(
                      scale: animation,
                      child: child,
                    );
                  },
                  child: Text(
                    '$_counter',
                    // This key causes the AnimatedSwitcher to interpret this as a ""
                    // child each time the count changes, so that it will begin its animation
                    // when the count changes.
                    key: ValueKey<int>(_counter),
                    style: Theme.of(context).textTheme.headline4,
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ),
    );
  }
}

Run

Simply copy the source code into your Flutter Project, Build and Run.

Reference.

Download code here.
Follow code author here.