What is the Flutter SlideTransition widget?
Flutter SlideTransition is a widget that allows you to animate the position of a child widget as it slides in and out of view. It takes two main inputs: a child widget and an animation. As the animation’s value changes over time, the child widget will appear to move or slide.
The animation that is passed to the SlideTransition is typically an Animation<Offset>. The Animation<Offset> object is used to define the starting and ending position of the child widget during the animation. The AnimationController controls the animation by starting, stopping, or reversing it. The SlideTransition will move the child widget to the position defined by the animation during the animation.
With SlideTransition you can create different sliding animations, like sliding in and out of view, sliding left or right, sliding up and down. You can customize the animation by changing the Animation object or the properties of the AnimationController that controls the animation.
Where the Flutter SlideTransition widget can be used
The SlideTransition widget can be used in a variety of ways in Flutter apps, some examples include:
- Animated navigation:
SlideTransitioncan be used to animate the transition between pages in a navigation stack by sliding in new pages from the left or right. - Drawer menus:
SlideTransitioncan be used to animate the opening and closing of a drawer menu by sliding it in from the left or right side of the screen. - Modal dialogs:
SlideTransitioncan be used to animate the appearance of modal dialogs by sliding them up from the bottom of the screen. - Bottom sheet:
SlideTransitioncan be used to animate the appearance of a bottom sheet by sliding it up from the bottom of the screen. - In-app notifications:
SlideTransitioncan be used to animate the appearance of in-app notifications by sliding them in from the top or bottom of the screen. - FAB (Floating Action Button) menus:
SlideTransitioncan be used to animate the opening and closing of a FAB menu by sliding it out from the FAB button. - Animating the size of widgets:
SlideTransitioncan be used to animate the size of a widget, for example, expanding or contracting a card. - Animating the position of a widget:
SlideTransitioncan be used to animate the position of a widget, for example, moving a widget from one position to another. - Carousels:
SlideTransitioncan be used to animate the transition between slides in a carousel by sliding them horizontally or vertically. - Image galleries:
SlideTransitioncan be used to animate the transition between images in a gallery by sliding them in from the left or right. - Tab bars:
SlideTransitioncan be used to animate the transition between tabs in a tab bar by sliding them horizontally. - Accordion-style widgets:
SlideTransitioncan be used to animate the expansion and contraction of accordion-style widgets by sliding them up or down. - Progress indicators:
SlideTransitioncan be used to animate a progress indicator by sliding a bar or dot across the screen. - Loading spinners:
SlideTransitioncan be used to animate a loading spinner by sliding a rotating element in or out of view. - Form inputs:
SlideTransitioncan be used to animate the appearance of form inputs by sliding them in when a form field is selected. - Error messages:
SlideTransitioncan be used to animate the appearance of error messages by sliding them in when a form field is invalid.
How to use the Flutter SlideTransition widget?
Here is an example of how you might use the SlideTransition widget to animate a grey box sliding in from the left of the screen:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<Offset> _animation;
bool _isBoxVisible = false;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500),
);
_animation = Tween<Offset>(
begin: Offset(-1, 0),
end: Offset.zero,
).animate(CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body:
Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text("Slide the box from the left"),
SizedBox(height: 20),
GestureDetector(
onTap: _toggleBoxVisibility,
child: Icon(Icons.play_arrow),
),
SizedBox(height: 20),
SlideTransition(
position: _animation,
child: _isBoxVisible
? Container(
width: 200,
height: 200,
color: Colors.grey,
)
: SizedBox.shrink(),
),
],
),
)
);
}
void _toggleBoxVisibility() {
setState(() {
_isBoxVisible = !_isBoxVisible;
if (_isBoxVisible) {
_animationController.forward();
} else {
_animationController.reverse();
}
});
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
}
the code can be broken down into the following sections:
- Class definition and variables
_animation: This is anAnimation<Offset>object that defines the starting and ending position of the grey box during the animation._animationController: This is anAnimationControllerobject that controls the animation by starting, stopping, or reversing it._isBoxVisible: This is a flag variable that indicates whether the grey box is currently visible or not.
initStatemethod
- This method is called when the state of the widget is created. It is where the
AnimationControllerandAnimation<Offset>objects are created and configured.
_toggleBoxVisibilityfunction
- This function toggles the value of
_isBoxVisibleand starts or stops the animation accordingly.
buildmethod
- This method is called every time the widget is rebuilt. It returns a widget tree that represents the user interface of the app. In this method, the
SlideTransitionwidget is wrapped around aContainerobject that represents the grey box. Thepositionproperty of theSlideTransitionis set to the_animationobject, so that the position of the grey box is controlled by the animation. Thechildproperty of theSlideTransitionis set to either the grey box or an emptySizedBoxdepending on the value of_isBoxVisible. GestureDetectorwidget detect the tap on the screen and_toggleBoxVisibilityfunction is called which toggles the value of_isBoxVisibleand starts or stops the animation accordingly.
disposemethod
- This method is called when the state of the widget is disposed. It is used to clean up any resources allocated by the
AnimationControllerandAnimation<Offset>objects.
Scaffoldwidget,AppBarwidget,IconButtonwidget andTextwidget, they are used to create the UI of the application, and they are not directly related to the animation.
The main idea is that when the user taps on the play arrow icon, the grey box should appear by sliding in from the left. When the user taps on the play arrow again, the grey box should disappear by sliding out to the left.
For this, the program uses a SlideTransition widget which is responsible to animate the position of the grey box as it slides in and out of view. The animation is defined by the _animation variable, which is an Animation<Offset> object that defines the starting and ending position of the grey box during the animation.
The _animationController variable is an AnimationController object that controls the animation by starting, stopping, or reversing it. The _isBoxVisible variable is a flag variable that indicates whether the grey box is currently visible or not.
In the build method, the SlideTransition widget is wrapped around a Container object that represents the grey box. The position property of the SlideTransition is set to the _animation object, so that the position of the grey box is controlled by the animation. The child property of the SlideTransition is set to either the grey box or an empty SizedBox depending on the value of _isBoxVisible.
When the user taps the play arrow icon, the _toggleBoxVisibility function is called, which toggles the value of _isBoxVisible and starts or stops the animation accordingly. The SlideTransition widget then animates the position
Slide menu with SlideTransition widget in Flutter

import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
late AnimationController _animationController;
late Animation<Offset> _animation;
bool _isMenuOpen = false;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 300),
);
_animation = Tween<Offset>(begin: Offset(0, -1), end: Offset(0, 0)).animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
void _toggleMenu() {
setState(() {
_isMenuOpen = !_isMenuOpen;
if (_isMenuOpen) {
_animationController.forward();
} else {
_animationController.reverse();
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
leading: IconButton(
icon: Icon(Icons.menu),
onPressed: _toggleMenu,
),
),
body:
GestureDetector(
onTap: () {
if (_isMenuOpen) {
_toggleMenu();
}
},
child: Stack(
children: [
Container(
child: Center(
child: Text("Hello, this is some text"),
),
),
SlideTransition(
position: _animation,
child: Container(
height: 300,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.all(
Radius.circular(20)
),
border: Border.all(width: 1)
),
child: Column(
children: [
SizedBox(height: 20),
Text(
'Menu',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
SizedBox(height: 20),
Expanded(
child: ListView(
children: [
ListTile(
title: Text("Menu Item 1"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 2"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 3"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 4"),
onTap: () {},
),
],
),
),
],
),
),
),
],
),
)
);
}
}
This code creates a simple Flutter app that demonstrates the use of the SlideTransition widget. The app has a basic layout with an app bar, a main body, and a sliding menu that appears from the left when the menu icon in the app bar is tapped.
- Variables:
_animationControlleris an instance ofAnimationControllerwhich is used to control the animation of the sliding menu. It sets the duration of the animation to 300 milliseconds._animationis an instance ofAnimation<Offset>which defines the animation of the sliding menu. It sets the starting point of the animation toOffset(0, -1)(off the top of the screen) and the end point toOffset(0, 0)(on the top of the screen), and uses aCurvedAnimationwith theCurves.easeInOutcurve._isMenuOpenis a boolean that keeps track of whether the menu is currently open or closed. It is set tofalseby default.
- Classes:
MyAppis aStatefulWidgetclass that returns theMaterialAppwidget. It has no additional functionality._MyAppStateis the state class that creates theMaterialAppwidget and sets the theme toprimarySwatch: Colors.blueand home page toMyHomePage().MyHomePageis aStatefulWidgetclass that returns theScaffoldwidget. It has no additional functionality._MyHomePageStateis the state class that creates theScaffoldwidget and sets the leading app bar icon to open and close the sliding menu by calling the_toggleMenu()function on press. It also useswith SingleTickerProviderStateMixinto provide a vsync for the animation controller.
- void functions:
main()function is the starting point of the app, where therunApp()function is called with theMyAppwidget as its argument._toggleMenu()function is called when the leading app bar icon is pressed. It toggles the state of the_isMenuOpenvariable and animates the menu accordingly. If the menu is currently closed, it calls_animationController.forward()to animate the menu sliding in from the top of the screen
- Main Widgets:
MaterialAppis the root widget of the app. It takes in thedebugShowCheckedModeBanner,title,theme, andhomeproperties. It sets thetitleto ‘Flutter Demo’, thethemetoprimarySwatch: Colors.blueand thehometoMyHomePage().Scaffoldwidget provides a basic layout structure for the app and creates the app bar, body and floating action button. TheappBarproperty sets the title of the app bar to ‘flutterassets.com’ and the leading icon button to open and close the menu by calling the_toggleMenu()function on press.Stackwidget overlays the menu on top of the body. It has two children:Containerwhich has aTextwidget with the text ‘Hello, this is some text’ andSlideTransitionwhich animates the sliding menu.SlideTransitionwidget takes in thepositionandchildproperties. Thepositionproperty is set to the_animationvariable and thechildproperty is aContainerwidget that holds the sliding menu.Containerwidget holds the sliding menu. It has aheightof 300, awidthofdouble.infinity, aBoxDecorationwithcolor: Colors.white,borderRadius: BorderRadius.all(Radius.circular(20)), andborder: Border.all(width: 1). It also has aColumnwidget withTextwidget with the text ‘Menu’ and anExpandedwidget that holds aListViewwith fourListTilewidgets, each with a title of ‘Menu Item 1’, ‘Menu Item 2’, ‘Menu Item 3’ and ‘Menu Item 4’ respectively.GestureDetectorwidget is wrapped around the stack, it listens for a tap event and if the menu is open it calls the_toggleMenu()function to close the menu.
- Functionality: The app has a sliding menu that appears from the left side of the screen when the menu icon button on the app bar is pressed. The menu is overlaid on top of the rest of the content and can be closed by tapping anywhere on the screen. The menu items are represented by
ListTilewidgets that are contained within aListView. EachListTilehas a title and an onTap function that currently does not have any functionality. The animation of the sliding menu is controlled by theAnimationControllerandAnimationclasses, which are used to animate the transition of the menu on and off the screen. The animation is set to a duration of 300 milliseconds and uses theCurves.easeInOutcurve. TheSingleTickerProviderStateMixinis used to provide a single ticker to the animation controller so that the animation runs smoothly.
Overall, the code is a basic example of how to create a sliding menu in a Flutter app using the Stack, SlideTransition and Animation classes. It could be further expanded upon to include additional functionality for the menu items, such as navigation to different pages in the app.
How to customize the sliding menu in Flutter
Here are a few examples of how you could customize the above code:
- Changing the background colour of the menu:
Container(
height: 300,
width: double.infinity,
decoration: BoxDecoration(
color: Colors.green, // changed color to green
borderRadius: BorderRadius.all(
Radius.circular(20)
),
border: Border.all(width: 1)
),
// ...
- Adding more menu items:
Expanded(
child: ListView(
children: [
ListTile(
title: Text("Menu Item 1"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 2"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 3"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 4"),
onTap: () {},
),
ListTile(
title: Text("Menu Item 5"), // added a new menu item
onTap: () {},
),
],
),
)
- Changing the animation duration:
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 500), // changed duration to 500 milliseconds
);
- Changing the animation curve:
_animation = Tween<Offset>(begin: Offset(0, -1), end: Offset(0, 0)).animate(
CurvedAnimation(
parent: _animationController,
curve: Curves.bounceIn, // changed curve to Curves.bounceIn
),
);
- Adding a custom icon for the menu button:
leading: IconButton(
icon: Icon(Icons.list), // changed icon to Icons.list
onPressed: _toggleMenu,
),
- Change the direction of the animation so that it slides in from the right instead of the left:
These are just a few examples of how the code could be customized. You could also add additional functionality to the menu items, such as navigating to different pages in the app, or change the layout of the menu to better fit your design.
_animation = Tween<Offset>(begin: Offset(1, 0), end: Offset(0, 0)).animate( // changed begin offset from Offset(0, -1) to Offset(1, 0)
CurvedAnimation(
parent: _animationController,
curve: Curves.easeInOut,
),
);
This is achieved by changing the value of the begin offset in the Tween animation. The begin offset is the starting point of the animation, and the end offset is the final point. So by changing the begin offset from Offset(0, -1) to Offset(1, 0), the animation starts from the right side of the screen instead of the left side.



