I am facing the following problem:
I have a StatefulWidget which can generate different view in case of state change:
class _HomePageState extends State<HomePage> {
bool _changed = false;
@override
Widget build(BuildContext context) {
return changed ? View2() : View1();
}
}
If I change a state _changed
to true
and hit the back button, a then the forward button, I would like my application to create fresh _HomePageState
and display a View1
, but currently the View2
is presented, so I believe that the state is persisted somehow.
How can I force rebuild of the widget's state?
Example app presenting the problem: link
Steps to reproduce:
- Open some site, eg. www.google.com
- Paste the link to the app https://issueapp.tiiny.site
- Change the state of the app by pressing a button
- Press browser's back button
- Press browser's forward button
GIF presenting the issue:
Full code which reproduces the problem:
import 'package:flutter/material.dart';
void main() => runApp(const Application());
class Application extends StatelessWidget {
const Application({super.key});
@override
Widget build(BuildContext context) => const HomePage();
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _changed = false;
@override
Widget build(BuildContext context) {
return Directionality(
textDirection: TextDirection.ltr,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(_changed ? "CHANGED" : "NOT CHANGED"),
ElevatedButton(
onPressed: () { setState(() { _changed = !_changed; }); },
child: const Text("CHANGE"),
),
],
),
);
}
}
This is because your screen is not changing, So browsers are not detecting. You can use
WillPopScope
see below code :