What does this mounted value do? Without the if (!mounted) return; there will be warning Do not use BuildContexts across async gaps. But how does it actually work?
What does the signature mean build(BuildContext context, [bool mounted = true])? Why the mounted is in the square brackets here?
@override
Widget build(BuildContext context, [bool mounted = true]) {
return PopupMenuButton<MenuAction>(
onSelected: (value) async {
switch (value) {
case MenuAction.logout:
final shouldLogOut = await showLogOutDialog(context);
if (!mounted) return;
if (shouldLogOut) {
context.read<AppState>().logOut();
}
...
>Solution :
A widget is mounted if it has state. If the widget is no longer mounted, i.e it has been closed or disposed, its state can no longer be updated. Therefore, we check if a widget is mounted to determine if its state can still be updated.
In more simple words if mounted is true the widget is visible on screen else it is disposed.