Skip to main content

Animated Navigation in Flutter

 

Introduction

By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition.

 

Introduction

By default, Flutter has no animation when navigating from one Screen to another Screen. But in this tutorial, we are going to learn how to animate the Screen Transition.

Table of Contents

  • Project Setup
  • Code
  • Result

Project Setup

Before directly applying to your existing project, practice the code in some example projects. For this tutorial, we are going to name our project screen_animation_tutorial. Open in VSCode or Android Studio.

After that, we will make two Screens. The first Screen will be the Starting screen and the next Screen will be the Final Screen. So go ahead and create two dart files under the lib folder.

The main.dart file code should look like this

Dart
import 'package:flutter/material.dart';
import 'package:screen_animation_tutorial/start_screen.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.yellow,
      ),
      home: StartScreen(),
    );
  }
}

 

The start_screen.dart should look like this.

Dart
import 'package:flutter/material.dart';
import 'package:screen_animation_tutorial/final_screen.dart';

class StartScreen extends StatelessWidget {
  const StartScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Start'),
      ),
      body: Container(
        color: Colors.yellow[200],
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Start',
                style: TextStyle(fontSize: 48.0),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (_) => FinalScreen(),
                    ),
                  );
                },
                child: Text(
                  'Final',
                  style: TextStyle(
                    fontSize: 32.0,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

The final_screen.dart should look like this.

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

class FinalScreen extends StatelessWidget {
  const FinalScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Final'),
      ),
      body: Container(
        color: Colors.red[200],
        child: Center(
          child: Text(
            'Final',
            style: TextStyle(fontSize: 48.0),
          ),
        ),
      ),
    );
  }
}

 

Run the app. It should look as below.

No Animation


Code

Now we will implement the animation.

So in the start_screen.dart we have put the code for navigation inside the ElevatedButton widget. 

Dart

onPressed: () {
  Navigator.push(
    context,
    MaterialPageRoute(
      builder: (_) => FinalScreen(),
    ),
  );
},

 

Replace the MaterialPageRoute with PageRouteBuilder. It creates a Route that delegates to builder callbacks.

Dart
PageRouteBuilder(
  pageBuilder: (BuildContext context,
                Animation<double> animation,
                Animation<double> secondaryAnimation) {},
  ),
);

 

Inside the pageBuilder curly braces we the return Final Screen.

Dart
pageBuilder: (BuildContext context,
              Animation<double> animation,
              Animation<double> secondaryAnimation) {
  return FinalScreen();
},

 

Now add transitionBuilder in the PageRouteBuilder.

Dart
transitionsBuilder:
	(context, animation, secondaryAnimation, child) {
},

 

Now it is the most interesting part.

Here we will put how do we want our animation. So I want pop-in animation. So I am going to use ScaleTransition. If you want the Scrolling animation you can use Sliding Animation. You can use a bunch of animation with Flutter. Go ahead and try out all. Here I am going to use ScaleTranstion.

Dart
transitionsBuilder:
(context, animation, secondaryAnimation, child) {
  return ScaleTransition(
    alignment: Alignment.center,
    scale: Tween<double>(begin: 0.1, end: 1).animate(
      CurvedAnimation(
        parent: animation,
        curve: Curves.bounceIn,
      ),
    ),
    child: child,
  );
},

 

Here we can also use custom duration using the transitionDuration field.

Dart
transitionDuration: Duration(seconds: 2),

 

So we have completed the tutorial. The basic types of animation are:

  1. FadeTransition
  2. SizeTransition
  3. AlignTransition
  4. ScaleTransition
  5. PositionedTransition

Here is the full code of start_screen.dart in case you missed or couldn't follow.

Dart
import 'package:flutter/material.dart';
import 'package:screen_animation_tutorial/final_screen.dart';

class StartScreen extends StatelessWidget {
  const StartScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Start'),
      ),
      body: Container(
        color: Colors.yellow[200],
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'Start',
                style: TextStyle(fontSize: 48.0),
              ),
              ElevatedButton(
                onPressed: () {
                  Navigator.push(
                    context,
                    PageRouteBuilder(
                      transitionsBuilder:
                          (context, animation, secondaryAnimation, child) {
                        return ScaleTransition(
                          alignment: Alignment.center,
                          scale: Tween<double>(begin: 0.1, end: 1).animate(
                            CurvedAnimation(
                              parent: animation,
                              curve: Curves.bounceIn,
                            ),
                          ),
                          child: child,
                        );
                      },
                      transitionDuration: Duration(seconds: 2),
                      pageBuilder: (BuildContext context,
                          Animation<double> animation,
                          Animation<double> secondaryAnimation) {
                        return FinalScreen();
                      },
                    ),
                  );
                },
                child: Text(
                  'Final',
                  style: TextStyle(
                    fontSize: 32.0,
                    fontWeight: FontWeight.w700,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

 

Run the app now.

Result

The final app looks like below.

Final App


Hope you enjoyed the tutorial and learned something new. If you have any problems comment below.

 

Comments

Popular posts from this blog

Flutter | Material Banner Tutorial

In this tutorial, we will create and display Material Banner in Flutter . Material Banners are displayed at the top of the screen . User interaction is required to dismiss the banner . Material Banner Material Banner alerts the user about action and p rovides some actions for the user to take . In brief, it alerts the user about an issue and the user address the issue . The user should dismiss the banner to remove it from the screen else it will be active. Syntax  ScaffoldMessenger.of(context).showMaterialBanner(MaterialBanner( content: content, actions: actions)) Code Here is our starting class. It is a stateless class and we will display a banner when the Button is pressed. class SnackBarTutorial extends StatelessWidget { const SnackBarTutorial({Key ? key}) : super ( key: key); @ override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text( "Material Banner"

How to create Snackbars in Flutter | Snackbar Tutorial

In this article, we will create and display different types of SnackBars in Flutter.  SnackBars in Flutter SnackBars are used to briefly display some information or inform the user about an action. For instance, when a user deletes a mail or message you may want to inform the user about the action. Also, the user can undo the action he performed by the undo button in the Snackbar . Syntax For creating a SnackBar, we use the following code. ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: content)); Inside the content field of SnackBar, we will pass the content. Any content can be passed inside it, but in practice, small messages with or without a button. Example Simple SnackBar class SnackBarTutorial extends StatelessWidget {   const SnackBarTutorial({Key? key}) : super (key: key);   @override   Widget build(BuildContext context) {     return

Flutter: DatePicker Tutorial both with Material and Cupertino Style

Introduction DatePicker is very important when you want the user to pick his / her date of birth or something else. In Flutter, implementing DatePicker is very easy and we will implement DatePicker in both Android or Material style and Cupertino or IOS style.  Table of contents Approach Project Setup Material Style DatePicker Cupertino Style DatePicker Conclusion Approach Flutter has widgets for everything and even for DatePicker. DatePicker widget is loaded with all needed animation and colours. So implementation is very easy.  Project Setup No extra plugins are required for this project and you can continue with your existing project. Here is the starting code. class DatePickerTutorial extends StatefulWidget { const DatePickerTutorial({Key? key}) : super (key: key); @ override _DatePickerTutorialState createState() => _DatePickerTutorialState(); } class _DatePickerTutorialState extends State<DatePick