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
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.
context.mounted
context.mounted
is an instance property of BuildContext
.BuildContext
is still mounted (i.e., part of the widget tree).BuildContext
to another function and want to verify that the widget is still active.mounted
State
class in Flutter.State
object is still active and its widget is still in the widget tree.State
class to check if it is safe to perform operations.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.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"),
),
),
);
}
}
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"),
),
),
);
}
}
context.mounted
when you're dealing with BuildContext in an asynchronous operation or passing it to another function.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.