context.go and push
- Flutter course
- Intermediate
- Lesson 68/99
- 4 min
Replace with context.go and stack with context.push.
context.go and context.push
context.go('/path') replaces the current route; it sets the navigation stack to the new path with no way back. context.push('/path') adds the new route on top of the stack; you can then go back with context.pop().
// Replace: no going back
context.go('/ayarlar');
// Push: can go back
context.push('/detay');Going back with context.pop
context.pop() removes the topmost route from the stack and returns to the previous screen. Routes added with push are removed with pop; routes set with go have no back stack, so pop does not work.
ElevatedButton(
onPressed: () => context.pop(),
child: const Text('Geri'),
)Practice Navigate with a button
Define a StatelessWidget named DetayScreen. In its Scaffold body, place an ElevatedButton inside a Center. Its onPressed should call context.go('/detay') and its child should be Text('Detay'). Print 'hazir' in main.
Starter code
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
// DetayScreen sınıfı tanımla
// Scaffold içinde Center ve ElevatedButton olsun
// onPressed ile /detay yoluna git
// Buton yazısı 'Detay' olsun
void main() {
// 'hazir' yazdır
}Sample solution
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
class DetayScreen extends StatelessWidget {
const DetayScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () => context.go('/detay'),
child: const Text('Detay'),
),
),
);
}
}
void main() {
print('hazir');
}Expected output
hazir
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the difference between context.go and context.push?
- go is async, push is sync
- go is faster, push is slower
- go replaces the stack, push adds on top of the stack Correct answer
- go works only on Android, push only on iOS
Explanation: context.go replaces the stack (no way back), context.push adds on top of the stack (can go back with context.pop). Speed, platform, and async/sync differences are irrelevant.
2 context.go call
ElevatedButton(
onPressed: () {
____;
},
child: const Text('Ayarlar'),
)
ElevatedButton(
onPressed: () {
context.go('/ayarlar');
},
child: const Text('Ayarlar'),
)
Explanation: In GoRouter you use context.go to switch screens. Navigator.go is not part of GoRouter, and context.route and context.build do not exist.
3 Navigation methods
| Term | Meaning |
|---|---|
context.go |
Replaces the stack |
context.push |
Adds to the stack |
context.pop |
Goes back |
GoRouter |
The router |