Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swipe to go back gesture flutter

How do i implement the swipe from the left to go back gesture in flutter? Not sure if it was already implemented automatically for iOS, but I wanted it for Android as well (as things are becoming gesture based).

like image 799
Tom O'Sullivan Avatar asked Apr 17 '18 21:04

Tom O'Sullivan


1 Answers

You can use CupertinoPageRoute() as Tom O'Sullivan said above.

However, if you want to customize it (eg. using custom transition duration) using PageRouteBuilders and get the same swipe to go back gesture, then you can override buildTransitions().

For iOS, the default PageTransitionBuilder is CupertinoPageTransitionsBuilder(). So we can use that in buildTransitions(). This automatically give us the swipe right to go back gesture.

Here's some sample code for the CustomPageRouteBuilder:

class CustomPageRouteBuilder<T> extends PageRoute<T> {
  final RoutePageBuilder pageBuilder;
  final PageTransitionsBuilder matchingBuilder = const CupertinoPageTransitionsBuilder(); // Default iOS/macOS (to get the swipe right to go back gesture)
  // final PageTransitionsBuilder matchingBuilder = const FadeUpwardsPageTransitionsBuilder(); // Default Android/Linux/Windows

  CustomPageRouteBuilder({this.pageBuilder});

  @override
  Color get barrierColor => null;

  @override
  String get barrierLabel => null;

  @override
  Widget buildPage(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation) {
    return pageBuilder(context, animation, secondaryAnimation);
  }

  @override
  bool get maintainState => true;

  @override
  Duration get transitionDuration => Duration(milliseconds: 900); // Can give custom Duration, unlike in MaterialPageRoute

  @override
  Widget buildTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return matchingBuilder.buildTransitions<T>(this, context, animation, secondaryAnimation, child);
  }
}

Then to go to a new page:

GestureDetector(
  onTap: () => Navigator.push(
    context,
    CustomPageRouteBuilder(pageBuilder: (context, animation, secondaryAnimation) => NewScreen()),
  ),
  child: ...,
)
like image 107
Rohan Kadkol Avatar answered Sep 28 '22 20:09

Rohan Kadkol