Created
September 8, 2024 05:25
-
-
Save eseidel/6e90caf80bc384d33122dc5b18df9d2e to your computer and use it in GitHub Desktop.
go_router counter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:go_router/go_router.dart'; | |
void main() { | |
runApp(const MyApp()); | |
} | |
/// The route configuration. | |
final GoRouter _router = GoRouter( | |
routes: <RouteBase>[ | |
GoRoute( | |
path: '/', | |
name: 'counter', | |
builder: (BuildContext context, GoRouterState state) { | |
final parameter = state.uri.queryParameters['c']; | |
final maybeCounter = parameter == null ? 0 : int.tryParse(parameter); | |
final counter = maybeCounter ?? 0; | |
return HomeScreen(counter: counter); | |
}, | |
), | |
], | |
); | |
class MyApp extends StatelessWidget { | |
/// Constructs a [MyApp] | |
const MyApp({super.key}); | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp.router( | |
routerConfig: _router, | |
); | |
} | |
} | |
class HomeScreen extends StatelessWidget { | |
const HomeScreen({super.key, required this.counter}); | |
final int counter; | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData( | |
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple), | |
useMaterial3: true, | |
), | |
home: MyHomePage(counter: counter), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
const MyHomePage({super.key, required this.counter}); | |
final int counter; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
backgroundColor: Theme.of(context).colorScheme.inversePrimary, | |
title: const Text('Flutter Demo Home Page'), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
const Text( | |
'You have pushed the button this many times:', | |
), | |
Text( | |
'$counter', | |
style: Theme.of(context).textTheme.headlineMedium, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: () { | |
context.goNamed('counter', queryParameters: {'c': '${counter + 1}'}); | |
}, | |
tooltip: 'Increment', | |
child: const Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment