Skip to content

Instantly share code, notes, and snippets.

@macoshita
Created February 27, 2020 00:22
Show Gist options
  • Save macoshita/129a4fe46f7080fcdbba77a2d380a871 to your computer and use it in GitHub Desktop.
Save macoshita/129a4fe46f7080fcdbba77a2d380a871 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomeScreen(),
);
}
}
class HomeScreen extends StatelessWidget {
final navigatorKey = GlobalKey<NavigatorState>();
final title = ValueNotifier<String>("A");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: ValueListenableBuilder<String>(
valueListenable: title,
builder: (_, title, __) {
return Text(title);
},
),
),
drawer: Drawer(
child: ListView(
children: [
DrawerHeader(child: Text("Menu")),
ListTile(
title: Text("Go to A"),
onTap: () {
// Scaffold の乗ってる navigator に対して pop して Drawer を閉じる
Navigator.of(context).pop();
// body の navigator に push してページ切り替え
navigatorKey.currentState.pushNamed("a");
}
),
ListTile(
title: Text("Go to B"),
onTap: () {
Navigator.of(context).pop();
navigatorKey.currentState.pushNamed("b");
}
),
],
),
),
body: Navigator(
key: navigatorKey,
initialRoute: "a",
onGenerateRoute: (settings) {
final builders = <String, WidgetBuilder>{
"a": (_) => PageA(),
"b": (_) => PageB(),
};
title.value = <String, String>{
"a": "Page A",
"b": "Page B",
}[settings.name];
return MaterialPageRoute<void>(builder: builders[settings.name]);
},
)
);
}
}
class PageA extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: Text("A"));
}
}
class PageB extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Center(child: Text("B"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment