Dispose widget when navigating to new route. You can call Navigator.pushReplacement
when routing between first and second screen.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( title: 'Navigation Basics', home: FirstRoute(), )); } class FirstRoute extends StatefulWidget { @override _FirstRouteState createState() => _FirstRouteState(); } class _FirstRouteState extends State<FirstRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('First Route'), ), body: RaisedButton( child: Text('Open route'), onPressed: () { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => SecondRoute()), ); }, ), ); } @override void dispose() { // Never called print("Disposing first route"); super.dispose(); } } class SecondRoute extends StatefulWidget { @override _SecondRouteState createState() => _SecondRouteState(); } class _SecondRouteState extends State<SecondRoute> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Second Route"), ), body: RaisedButton( onPressed: () { Navigator.pushReplacement( context, MaterialPageRoute(builder: (context) => FirstRoute()), ); }, child: Text('Go back!'), ), ); } @override void dispose() { print("Disposing second route"); super.dispose(); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.