Open In App

Flutter – Implement Animated TextSwitcher

Last Updated : 19 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

TextSwitcher is specifically designed for switching between different text with animations. It’s commonly used to create smooth text transitions. There is no direct widget of TextWsitcher in Flutter but we can Implement this by using AnimatedSwitcher.This widget allows us to smoothly transition between different child widgets, including text widgets, and you can customize the transition animations. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

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,
      home: TextSwitcherDemo(),
    );
  }
}


Step 5: Create TextSwitcherDemo Class

In this class we are going to implement the TextSwitcher with Animation. This class cotains a widget called AnimatedSwitcher widget, which is responsible for switching the text with an animation.In this class we created a floating action button by clicking which transition between the text will appear with some animation effect. Comments are added for better understanding.

AnimatedSwitcher(
duration: Duration(seconds: 1), // Animation duration
transitionBuilder: (Widget child, Animation<double> animation) {
// Define the animation for sliding in and out
final offsetAnimation = Tween<Offset>(
begin: Offset(1.0, 0.0), // Start from the right
end: Offset(0.0, 0.0), // End at the center
).animate(animation);
return SlideTransition(
position: offsetAnimation,
child: child,
);
},
child: Text(
texts[currentIndex], // Display the current text
key: ValueKey<String>(
texts[currentIndex]), // Key for identifying the text widget
style: TextStyle(fontSize: 24), // Text style
),
),

Dart




class TextSwitcherDemo extends StatefulWidget {
  @override
  _TextSwitcherDemoState createState() => _TextSwitcherDemoState();
}
  
class _TextSwitcherDemoState extends State<TextSwitcherDemo> {
  // List of text values to switch between
  List<String> texts = ["GFG Text 1", "GFG Text 2", "GFG Text 3"];
  int currentIndex = 0; // Index to track the currently displayed text
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Text Switcher Demo"), // App bar title
      ),
      body: Center(
        child: AnimatedSwitcher(
          duration: Duration(seconds: 1), // Animation duration
          transitionBuilder: (Widget child, Animation<double> animation) {
            // Define the animation for sliding in and out
            final offsetAnimation = Tween<Offset>(
              begin: Offset(1.0, 0.0), // Start from the right
              end: Offset(0.0, 0.0), // End at the center
            ).animate(animation);
            return SlideTransition(
              position: offsetAnimation,
              child: child,
            );
          },
          child: Text(
            texts[currentIndex], // Display the current text
            key: ValueKey<String>(
                texts[currentIndex]), // Key for identifying the text widget
            style: TextStyle(fontSize: 24), // Text style
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            currentIndex =
                (currentIndex + 1) % texts.length; // Cycle through the texts
          });
        },
        child: Icon(Icons.swap_horiz), // Button for switching text
      ),
    );
  }
}


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,
      home: TextSwitcherDemo(),
    );
  }
}
  
class TextSwitcherDemo extends StatefulWidget {
  @override
  _TextSwitcherDemoState createState() => _TextSwitcherDemoState();
}
  
class _TextSwitcherDemoState extends State<TextSwitcherDemo> {
  // List of text values to switch between
  List<String> texts = ["GFG Text 1", "GFG Text 2", "GFG Text 3"];
  int currentIndex = 0; // Index to track the currently displayed text
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Text Switcher Demo"), // App bar title
      ),
      body: Center(
        child: AnimatedSwitcher(
          duration: Duration(seconds: 1), // Animation duration
          transitionBuilder: (Widget child, Animation<double> animation) {
            // Define the animation for sliding in and out
            final offsetAnimation = Tween<Offset>(
              begin: Offset(1.0, 0.0), // Start from the right
              end: Offset(0.0, 0.0), // End at the center
            ).animate(animation);
            return SlideTransition(
              position: offsetAnimation,
              child: child,
            );
          },
          child: Text(
            texts[currentIndex], // Display the current text
            key: ValueKey<String>(
                texts[currentIndex]), // Key for identifying the text widget
            style: TextStyle(fontSize: 24), // Text style
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          setState(() {
            currentIndex =
                (currentIndex + 1) % texts.length; // Cycle through the texts
          });
        },
        child: Icon(Icons.swap_horiz), // Button for switching text
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads