import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
void main() {
runApp(MyApp());
}
final GoRouter _router = GoRouter(
routes: [
GoRoute(
path: '/',
builder: (context, state) => HomePage(),
),
GoRoute(
path: '/details',
builder: (context, state) => DetailsPage(),
),
],
);
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp.router(
routerConfig: _router,
title: 'GoRouter Demo',
theme: ThemeData(primarySwatch: Colors.blue),
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('HomePage')),
body: Center(
child: ElevatedButton(
onPressed: () {
context.go('/details');
},
child: Text('Go to Details'),
),
),
);
}
}
class DetailsPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('DetailsPage')),
body: Center(
child: ElevatedButton(
onPressed: () {
context.go('/');
},
child: Text('Back to Home'),
),
),
);
}
}
We created a GoRouter instance with two routes: '/' for HomePage and '/details' for DetailsPage. The MaterialApp.router uses this router configuration to handle navigation.
In HomePage, pressing the button calls context.go('/details') to navigate to the details page. In DetailsPage, pressing the button calls context.go('/') to go back to the home page.
This setup uses GoRouter's simple API to manage navigation declaratively and cleanly.