Skip to content

Instantly share code, notes, and snippets.

@johnpryan
Last active January 16, 2020 22:23
Show Gist options
  • Save johnpryan/3ab92c3834e0235411be303a34101774 to your computer and use it in GitHub Desktop.
Save johnpryan/3ab92c3834e0235411be303a34101774 to your computer and use it in GitHub Desktop.
Drawer navigation in Flutter
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