Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the mounted value and how does it work?

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();
            }
            ...

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading