I noticed that navigation in my Flutter Web app not working well if I’m using back button from browser.
For example:
- Go from home page to first page
- Go from first page to second page
- Coming back to the first page
- I cannot back to home page, until I click on any place on screen.
It only happens in Flutter Web. In Android app it’s working fine
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
title: 'Genistree',
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.yellowAccent,
child: ElevatedButton(onPressed: () {
// Get.to(FirstPage());
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => FirstPage(),
),
);
}, child: Text("Go to 1st page"),
),),
);
}
}
class FirstPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.blue,
child: ElevatedButton(onPressed: () {
// Get.to(SecondPage());
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => SecondPage(),
),
);
}, child: Text("Go to 2st page"),
),),);
}
}
class SecondPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.red,
),
);
}
}
2
Answers
This issue might be related to the way Flutter handles routing and navigation on the web. You can try using WillPopScope widget to handle back button behavior explicitly in your Flutter web app.
I tried a bunch of solutions, but nothing worked for me except this one.
It remembers the stack’s navigation.