I know this sounds crazy, so maybe someone can point to me where am I wrong and maybe if I misunderstand some basic way Flutter works.
Here is some very basic code.
Run the app, click on the Floating Action Button and back 5 times. What I would expect is that BarPage is now gone from the memory.
Open Flutter Dev Tools, Memory tab and do a heap dump, check your instances. Here is what I got. 2 instances of BarPage still in memory. I did 3 separate dumps in case GC didn't trigger or something.
Here is the code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
onGenerateRoute: (RouteSettings settings) {
final args = settings.arguments;
switch (settings.name) {
case "/bar":
return MaterialPageRoute(builder: (_) => BarPage());
}
},
);
}
}
class HomePage extends StatelessWidget {
HomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Home screen'),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context).pushNamed("/bar");
},
child: const Icon(Icons.navigation),
backgroundColor: Colors.green,
),
);
}
}
class BarPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Bar screen'),
),
);
}
}
