Skip to content

Instantly share code, notes, and snippets.

@beroso
Last active August 31, 2022 05:06
Show Gist options
  • Select an option

  • Save beroso/250b450f0c59b1cda6add362e7d6f7c4 to your computer and use it in GitHub Desktop.

Select an option

Save beroso/250b450f0c59b1cda6add362e7d6f7c4 to your computer and use it in GitHub Desktop.
Drawer with Navigator

Drawer with Navigator

Created with <3 with dartpad.dev.

import 'dart:math';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Drawer with Navigator',
debugShowCheckedModeBanner: false,
home: MainScreen(),
);
}
}
final _navigatorKey = GlobalKey();
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('My page'),
),
drawer: Drawer(
child: Navigator(
key: _navigatorKey, // Sets the navigator key
initialRoute: '/',
onGenerateRoute: (routeSettings) {
if (routeSettings.name == '/') {
// Render initial drawer content
return MaterialPageRoute(
builder: (context) => ListView(
children: [
const UserAccountsDrawerHeader(
accountEmail: Text("jd@mail.com"),
accountName: Text("John Doe"),
currentAccountPicture: CircleAvatar(
child: Text("JD"),
),
),
for (var i = 0; i < 3; i++)
SubMenuItem(path: '${i + 1}'),
],
),
);
}
return null;
},
),
),
body: const Center(child: Text('Main page content')),
);
}
}
class SubMenu extends StatelessWidget {
final String path;
const SubMenu({super.key, required this.path});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Menu $path')),
body: ListView(
children: [
for (var i = 0; i <= Random().nextInt(5); i++)
SubMenuItem(path: '$path.${i + 1}'),
],
),
);
}
}
class SubMenuItem extends StatelessWidget {
final String path;
const SubMenuItem({super.key, required this.path});
@override
Widget build(BuildContext context) {
return ListTile(
title: Text('Go to menu $path'),
trailing: const Icon(Icons.keyboard_arrow_right),
onTap: () {
// Pushing a page in the nested navigation
Navigator.of(_navigatorKey.currentContext!).push(
MaterialPageRoute(
builder: (context) => SubMenu(path: path),
),
);
},
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment