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:
SlideTransition
can be used to animate the transition between pages in a navigation stack by sliding in new pages from the left or right. - Drawer menus:
SlideTransition
can 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:
SlideTransition
can be used to animate the appearance of modal dialogs by sliding them up from the bottom of the screen. - Bottom sheet:
SlideTransition
can be used to animate the appearance of a bottom sheet by sliding it up from the bottom of the screen. - In-app notifications:
SlideTransition
can 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:
SlideTransition
can 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:
SlideTransition
can be used to animate the size of a widget, for example, expanding or contracting a card. - Animating the position of a widget:
SlideTransition
can be used to animate the position of a widget, for example, moving a widget from one position to another. - Carousels:
SlideTransition
can be used to animate the transition between slides in a carousel by sliding them horizontally or vertically. - Image galleries:
SlideTransition
can be used to animate the transition between images in a gallery by sliding them in from the left or right. - Tab bars:
SlideTransition
can be used to animate the transition between tabs in a tab bar by sliding them horizontally. - Accordion-style widgets:
SlideTransition
can be used to animate the expansion and contraction of accordion-style widgets by sliding them up or down. - Progress indicators:
SlideTransition
can be used to animate a progress indicator by sliding a bar or dot across the screen. - Loading spinners:
SlideTransition
can be used to animate a loading spinner by sliding a rotating element in or out of view. - Form inputs:
SlideTransition
can be used to animate the appearance of form inputs by sliding them in when a form field is selected. - Error messages:
SlideTransition
can 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 anAnimationController
object 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.
initState
method
- This method is called when the state of the widget is created. It is where the
AnimationController
andAnimation<Offset>
objects are created and configured.
_toggleBoxVisibility
function
- This function toggles the value of
_isBoxVisible
and starts or stops the animation accordingly.
build
method
- 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
SlideTransition
widget is wrapped around aContainer
object that represents the grey box. Theposition
property of theSlideTransition
is set to the_animation
object, so that the position of the grey box is controlled by the animation. Thechild
property of theSlideTransition
is set to either the grey box or an emptySizedBox
depending on the value of_isBoxVisible
. GestureDetector
widget detect the tap on the screen and_toggleBoxVisibility
function is called which toggles the value of_isBoxVisible
and starts or stops the animation accordingly.
dispose
method
- This method is called when the state of the widget is disposed. It is used to clean up any resources allocated by the
AnimationController
andAnimation<Offset>
objects.
Scaffold
widget,AppBar
widget,IconButton
widget andText
widget, 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:
_animationController
is an instance ofAnimationController
which is used to control the animation of the sliding menu. It sets the duration of the animation to 300 milliseconds._animation
is 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 aCurvedAnimation
with theCurves.easeInOut
curve._isMenuOpen
is a boolean that keeps track of whether the menu is currently open or closed. It is set tofalse
by default.
- Classes:
MyApp
is aStatefulWidget
class that returns theMaterialApp
widget. It has no additional functionality._MyAppState
is the state class that creates theMaterialApp
widget and sets the theme toprimarySwatch: Colors.blue
and home page toMyHomePage()
.MyHomePage
is aStatefulWidget
class that returns theScaffold
widget. It has no additional functionality._MyHomePageState
is the state class that creates theScaffold
widget and sets the leading app bar icon to open and close the sliding menu by calling the_toggleMenu()
function on press. It also useswith SingleTickerProviderStateMixin
to provide a vsync for the animation controller.
- void functions:
main()
function is the starting point of the app, where therunApp()
function is called with theMyApp
widget as its argument._toggleMenu()
function is called when the leading app bar icon is pressed. It toggles the state of the_isMenuOpen
variable 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:
MaterialApp
is the root widget of the app. It takes in thedebugShowCheckedModeBanner
,title
,theme
, andhome
properties. It sets thetitle
to ‘Flutter Demo’, thetheme
toprimarySwatch: Colors.blue
and thehome
toMyHomePage()
.Scaffold
widget provides a basic layout structure for the app and creates the app bar, body and floating action button. TheappBar
property 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.Stack
widget overlays the menu on top of the body. It has two children:Container
which has aText
widget with the text ‘Hello, this is some text’ andSlideTransition
which animates the sliding menu.SlideTransition
widget takes in theposition
andchild
properties. Theposition
property is set to the_animation
variable and thechild
property is aContainer
widget that holds the sliding menu.Container
widget holds the sliding menu. It has aheight
of 300, awidth
ofdouble.infinity
, aBoxDecoration
withcolor: Colors.white
,borderRadius: BorderRadius.all(Radius.circular(20))
, andborder: Border.all(width: 1)
. It also has aColumn
widget withText
widget with the text ‘Menu’ and anExpanded
widget that holds aListView
with fourListTile
widgets, each with a title of ‘Menu Item 1’, ‘Menu Item 2’, ‘Menu Item 3’ and ‘Menu Item 4’ respectively.GestureDetector
widget 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
ListTile
widgets that are contained within aListView
. EachListTile
has a title and an onTap function that currently does not have any functionality. The animation of the sliding menu is controlled by theAnimationController
andAnimation
classes, 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.easeInOut
curve. TheSingleTickerProviderStateMixin
is 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.