flutter slidetransition menu

What is the Flutter SlideTransition widget and how to use it

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:

  1. 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.
  2. 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.
  3. Modal dialogs: SlideTransition can be used to animate the appearance of modal dialogs by sliding them up from the bottom of the screen.
  4. Bottom sheet: SlideTransition can be used to animate the appearance of a bottom sheet by sliding it up from the bottom of the screen.
  5. 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.
  6. 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.
  7. Animating the size of widgets: SlideTransition can be used to animate the size of a widget, for example, expanding or contracting a card.
  8. 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.
  9. Carousels: SlideTransition can be used to animate the transition between slides in a carousel by sliding them horizontally or vertically.
  10. Image galleries: SlideTransition can be used to animate the transition between images in a gallery by sliding them in from the left or right.
  11. Tab bars: SlideTransition can be used to animate the transition between tabs in a tab bar by sliding them horizontally.
  12. Accordion-style widgets: SlideTransition can be used to animate the expansion and contraction of accordion-style widgets by sliding them up or down.
  13. Progress indicators: SlideTransition can be used to animate a progress indicator by sliding a bar or dot across the screen.
  14. Loading spinners: SlideTransition can be used to animate a loading spinner by sliding a rotating element in or out of view.
  15. Form inputs: SlideTransition can be used to animate the appearance of form inputs by sliding them in when a form field is selected.
  16. 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:

  1. Class definition and variables
  • _animation: This is an Animation<Offset> object that defines the starting and ending position of the grey box during the animation.
  • _animationController: This is an AnimationController 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.
  1. initState method
  • This method is called when the state of the widget is created. It is where the AnimationController and Animation<Offset> objects are created and configured.
  1. _toggleBoxVisibility function
  • This function toggles the value of _isBoxVisible and starts or stops the animation accordingly.
  1. 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 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.
  • 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.
  1. 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 and Animation<Offset> objects.
  1. Scaffold widget, AppBar widget, IconButton widget and Text 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

flutter slidetransition menu
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.

  1. Variables:
  • _animationController is an instance of AnimationController 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 of Animation<Offset> which defines the animation of the sliding menu. It sets the starting point of the animation to Offset(0, -1) (off the top of the screen) and the end point to Offset(0, 0) (on the top of the screen), and uses a CurvedAnimation with the Curves.easeInOut curve.
  • _isMenuOpen is a boolean that keeps track of whether the menu is currently open or closed. It is set to false by default.
  1. Classes:
  • MyApp is a StatefulWidget class that returns the MaterialApp widget. It has no additional functionality.
  • _MyAppState is the state class that creates the MaterialApp widget and sets the theme to primarySwatch: Colors.blue and home page to MyHomePage().
  • MyHomePage is a StatefulWidget class that returns the Scaffold widget. It has no additional functionality.
  • _MyHomePageState is the state class that creates the Scaffold widget and sets the leading app bar icon to open and close the sliding menu by calling the _toggleMenu() function on press. It also uses with SingleTickerProviderStateMixin to provide a vsync for the animation controller.
  1. void functions:
  • main() function is the starting point of the app, where the runApp() function is called with the MyApp 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
  1. Main Widgets:
  • MaterialApp is the root widget of the app. It takes in the debugShowCheckedModeBanner, title, theme, and home properties. It sets the title to ‘Flutter Demo’, the theme to primarySwatch: Colors.blue and the home to MyHomePage().
  • Scaffold widget provides a basic layout structure for the app and creates the app bar, body and floating action button. The appBar 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 a Text widget with the text ‘Hello, this is some text’ and SlideTransition which animates the sliding menu.
  • SlideTransition widget takes in the position and child properties. The position property is set to the _animation variable and the child property is a Container widget that holds the sliding menu.
  • Container widget holds the sliding menu. It has a height of 300, a width of double.infinity, a BoxDecoration with color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(20)), and border: Border.all(width: 1). It also has a Column widget with Text widget with the text ‘Menu’ and an Expanded widget that holds a ListView with four ListTile 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.
  1. 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 a ListView. Each ListTile has a title and an onTap function that currently does not have any functionality. The animation of the sliding menu is controlled by the AnimationController and Animation 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 the Curves.easeInOut curve. The SingleTickerProviderStateMixin 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:

  1. 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)
  ),
  // ...
  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: () {},
      ),
    ],
  ),
)
  1. Changing the animation duration:
_animationController = AnimationController(
  vsync: this,
  duration: Duration(milliseconds: 500), // changed duration to 500 milliseconds
);
  1. 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
  ),
);
  1. Adding a custom icon for the menu button:
leading: IconButton(
  icon: Icon(Icons.list), // changed icon to Icons.list
  onPressed: _toggleMenu,
),
  1. 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.