Skip to content

Instantly share code, notes, and snippets.

@MelbourneDeveloper
Created June 25, 2023 07:13
Show Gist options
  • Select an option

  • Save MelbourneDeveloper/c2250d935f351f455d8842d0f704d4fe to your computer and use it in GitHub Desktop.

Select an option

Save MelbourneDeveloper/c2250d935f351f455d8842d0f704d4fe to your computer and use it in GitHub Desktop.
Navigation Extension
import 'package:flutter/material.dart';
extension NavigationExtension on BuildContext {
Future<void> navigateTo(String routeName, {Object? arguments}) {
return Navigator.pushNamed(this, routeName, arguments: arguments);
}
}
void main() {
runApp(MaterialApp(
title: 'Navigation Extension Demo',
initialRoute: '/',
routes: {
'/': (context) => const FirstScreen(),
'/second': (context) => const SecondScreen(),
},
));
}
class FirstScreen extends StatelessWidget {
const FirstScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('First Screen'),
),
body: Center(
child: ElevatedButton(
child: const Text('Go to second screen'),
onPressed: () {
context.navigateTo('/second');
},
),
),
);
}
class SecondScreen extends StatelessWidget {
const SecondScreen({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: const Text('Second Screen'),
),
body: const Center(
child: Text('You are on the second screen!'),
),
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment