admin管理员组

文章数量:1127084

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

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

Share Improve this question asked Jan 9 at 5:15 Aryan BishtAryan Bisht 14910 bronze badges 2
  • Both are coming from the same place(BuildContext). statefulWidget extend BuildContext and provide this getting – Md. Yeasin Sheikh Commented Jan 9 at 5:24
  • Both of them check whether the widget is attached to the widget tree or not (whether widget is currently displayed on screen or not). while mounted is inherited from StatefulWidget and context.mounted is encapsulated within BuildContext. – A-E Commented Jan 9 at 5:38
Add a comment  | 

1 Answer 1

Reset to default 0

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

  • Introduced in Flutter 3.10, context.mounted is an instance property of BuildContext.
  • It allows checking whether the widget associated with the given BuildContext is still mounted (i.e., part of the widget tree).
  • Useful in asynchronous callbacks or when you pass BuildContext to another function and want to verify that the widget is still active.

2. mounted

  • A property of the State class in Flutter.
  • Indicates whether the State object is still active and its widget is still in the widget tree.
  • Typically used within the same State class to check if it is safe to perform operations.

Key Difference

  • context.mounted is tied to the BuildContext and can be accessed anywhere the BuildContext is available.
  • mounted is specific to the State object and can only be accessed within the State class.

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

  • Use context.mounted when you're dealing with BuildContext in an asynchronous operation or passing it to another function.
  • Use mounted for simple state management within the State class.

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

本文标签: Difference between contextmounted and mounted in flutterStack Overflow