Last active
January 16, 2020 22:23
-
-
Save johnpryan/3ab92c3834e0235411be303a34101774 to your computer and use it in GitHub Desktop.
Drawer navigation in Flutter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/cupertino.dart'; | |
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MaterialApp( | |
home: RootPage(), | |
)); | |
} | |
class Destination { | |
final String name; | |
final String routeName; | |
final IconData iconData; | |
Destination(this.name, this.routeName, this.iconData); | |
} | |
final List<Destination> destinations = [ | |
Destination('Home', '/', Icons.dashboard), | |
Destination('Metrics', '/metrics', Icons.show_chart), | |
Destination('Settings', '/settings', Icons.settings), | |
]; | |
GlobalKey _navigatorKey = GlobalKey(); | |
class RootPage extends StatefulWidget { | |
@override | |
_RootPageState createState() => _RootPageState(); | |
} | |
class _RootPageState extends State<RootPage> { | |
Destination destination = destinations.first; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar(), | |
drawer: Drawer( | |
child: Column( | |
children: [ | |
DrawerHeader( | |
child: Center( | |
child: Text( | |
'MyApp', | |
style: Theme.of(context).textTheme.headline, | |
), | |
), | |
), | |
...destinations.map((d) { | |
return ListTile( | |
title: Text(d.name), | |
leading: Icon(d.iconData), | |
selected: d == destination, | |
onTap: () => _changePage(d), | |
); | |
}), | |
], | |
), | |
), | |
body: Navigator( | |
key: _navigatorKey, | |
onGenerateRoute: (settings) { | |
var destination = | |
destinations.firstWhere((d) => d.routeName == settings.name); | |
return PageRouteBuilder( | |
pageBuilder: (context, animation, secondaryAnimation) { | |
return PageHost(destination); | |
}, transitionsBuilder: | |
(context, animation, secondaryAnimation, child) { | |
var curveTween = CurveTween(curve: Curves.easeInQuart); | |
return FadeTransition( | |
opacity: animation.drive(curveTween), | |
child: child, | |
); | |
}); | |
}, | |
), | |
); | |
} | |
void _changePage(Destination d) { | |
var navState = _navigatorKey.currentState as NavigatorState; | |
navState.pushNamed(d.routeName); | |
setState(() { | |
destination = d; | |
}); | |
Navigator.of(context).pop(); | |
} | |
} | |
class PageHost extends StatelessWidget { | |
final Destination destination; | |
PageHost(this.destination); | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
child: Center( | |
child: Text(destination.name, style: Theme.of(context).textTheme.display3,), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment