Flutter – AnimatedSwitcher Widget

The AnimatedSwitcher widget in Flutter is used to animate the transition between two or more widgets with a smooth animation. It’s often used when you want to switch the display of different widgets within the same space and provide a visual transition effect between them. In this article, we are going to implement the AnimatedSwitcher widget and explore some properties of it. A sample video is given below to get an idea about what we are going to do in this article.

Basic Syntax of AnimatedSwitcher

AnimatedSwitcher(
duration: Duration(milliseconds: 500), // Animation duration
child: /* Your child widget */,
)

Required Tools

To build this app, you need the following items installed on your machine:

  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      title: 'AnimatedSwitcher Example',
      home: AnimatedSwitcherExample(),
    );
  }
}


Step 5: Create AnimatedSwitcherExample Class

In this class we are going to Implement the AnimatedSwitcher widget that help to create a transition between two widgets. Comments are added for better understanding.

 AnimatedSwitcher(
duration: Duration(seconds: 1), // Animation duration
child: _showFirst
? Container(
key: ValueKey<int>(1), // Unique key for the first widget
width: 200,
height: 200,
color: Colors.blue,
child: Center(
child: Text(
'Widget 1',
style: TextStyle(
fontSize: 24,
color: Colors.white,
),
),
),
)
: Container(
key: ValueKey<int>(2), // Unique key for the second widget
width: 200,
height: 200,
color: Colors.green,
child: Center(
child: Text(
'Widget 2',
style: TextStyle(
fontSize: 24,
color: Colors.white,
),
),
),
),
),

Dart




class AnimatedSwitcherExample extends StatefulWidget {
  @override
  _AnimatedSwitcherExampleState createState() =>
      _AnimatedSwitcherExampleState();
}
  
class _AnimatedSwitcherExampleState extends State<AnimatedSwitcherExample> {
  bool _showFirst = true; // Track which widget to display
  
  void _toggleWidgets() {
    setState(() {
      _showFirst = !_showFirst; // Toggle between two widgets
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedSwitcher Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            AnimatedSwitcher(
              duration: Duration(seconds: 1), // Animation duration
              child: _showFirst
                  ? Container(
                      key: ValueKey<int>(1), // Unique key for the first widget
                      width: 200,
                      height: 200,
                      color: Colors.blue,
                      child: Center(
                        child: Text(
                          'Widget 1',
                          style: TextStyle(
                            fontSize: 24,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )
                  : Container(
                      key: ValueKey<int>(2), // Unique key for the second widget
                      width: 200,
                      height: 200,
                      color: Colors.green,
                      child: Center(
                        child: Text(
                          'Widget 2',
                          style: TextStyle(
                            fontSize: 24,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _toggleWidgets,
              child: Text('Toggle Widgets'),
            ),
          ],
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      title: 'AnimatedSwitcher Example',
      home: AnimatedSwitcherExample(),
    );
  }
}
  
class AnimatedSwitcherExample extends StatefulWidget {
  @override
  _AnimatedSwitcherExampleState createState() =>
      _AnimatedSwitcherExampleState();
}
  
class _AnimatedSwitcherExampleState extends State<AnimatedSwitcherExample> {
  bool _showFirst = true; // Track which widget to display
  
  void _toggleWidgets() {
    setState(() {
      _showFirst = !_showFirst; // Toggle between two widgets
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('AnimatedSwitcher Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            AnimatedSwitcher(
              duration: Duration(seconds: 1), // Animation duration
              child: _showFirst
                  ? Container(
                      key: ValueKey<int>(1), // Unique key for the first widget
                      width: 200,
                      height: 200,
                      color: Colors.blue,
                      child: Center(
                        child: Text(
                          'Widget 1',
                          style: TextStyle(
                            fontSize: 24,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    )
                  : Container(
                      key: ValueKey<int>(2), // Unique key for the second widget
                      width: 200,
                      height: 200,
                      color: Colors.green,
                      child: Center(
                        child: Text(
                          'Widget 2',
                          style: TextStyle(
                            fontSize: 24,
                            color: Colors.white,
                          ),
                        ),
                      ),
                    ),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: _toggleWidgets,
              child: Text('Toggle Widgets'),
            ),
          ],
        ),
      ),
    );
  }
}


Output: