flutter

Difference between context.mounted and mounted in flutter


Can some explain me difference between context.mounted and mounted in flutter? I am not sure when to use which so most of the time I use them interchangeable. Please explain me this


Solution

  • In Flutter, context.mounted and mounted are used to check whether a widget is still part of the widget tree before performing certain operations, especially asynchronous ones. However, they differ in how they are accessed.


    1. context.mounted


    2. mounted


    Key Difference


    Examples

    Using context.mounted

    import 'package:flutter/material.dart';
    
    class ExampleWidget extends StatefulWidget {
      @override
      State<ExampleWidget> createState() => _ExampleWidgetState();
    }
    
    class _ExampleWidgetState extends State<ExampleWidget> {
      Future<void> fetchData(BuildContext context) async {
        // Simulate a network request
        await Future.delayed(Duration(seconds: 2));
    
        // Use context.mounted to check if the widget is still active
        if (context.mounted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(content: Text("Data fetched successfully!")),
          );
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("Context Mounted Example")),
          body: Center(
            child: ElevatedButton(
              onPressed: () => fetchData(context),
              child: Text("Fetch Data"),
            ),
          ),
        );
      }
    }
    

    Using mounted

    import 'package:flutter/material.dart';
    
    class ExampleWidget extends StatefulWidget {
      @override
      State<ExampleWidget> createState() => _ExampleWidgetState();
    }
    
    class _ExampleWidgetState extends State<ExampleWidget> {
      bool _loading = false;
    
      Future<void> fetchData() async {
        setState(() {
          _loading = true;
        });
    
        // Simulate a network request
        await Future.delayed(Duration(seconds: 2));
    
        // Use mounted to check if the widget is still active
        if (mounted) {
          setState(() {
            _loading = false;
          });
        }
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("Mounted Example")),
          body: Center(
            child: ElevatedButton(
              onPressed: _loading ? null : fetchData,
              child: Text(_loading ? "Loading..." : "Fetch Data"),
            ),
          ),
        );
      }
    }
    

    When to Use

    Both are essential for avoiding potential errors when interacting with widgets that might no longer exist in the widget tree.