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. 👌
Note: to better understand when you should check if a widget is mounted, watch this video: