Up until recently, it wasn't possible to check if a StatelessWidget
was mounted in Flutter.
But since Flutter 3.7, BuildContext
itself has a mounted
property! 🎉
This makes it easy to check if any widget is mounted, just like this:
// inside any widget
@override
Widget build(BuildContext context) {
return ElevatedButton(
child: const Text('Submit'),
onPressed: () async {
await doSomeAsyncWork(); // a method that returns a Future
if (context.mounted) {
Navigator.of(context).pop();
}
},
);
}
That's a great quality-of-life improvement. 👌
sponsor

Level up your Flutter app’s performance. Get full visibility into your Flutter app’s performance, including crashes, exceptions in Dart, network health, custom traces, and more. Solve your trickiest issues, optimize user journeys, and wow your end users - again and again.
Note: to better understand when you should check if a widget is mounted, watch this video: