So in my app, I want to make an Ajax request as soon as the widget is mounted, not in initState(). Similar to ComponentWillMount() in react
7 Answers
if the Widget has not mounted then return. Do it before the setState method
if (!mounted) return;
setState(() {});
or
if (mounted) {
//Do something
};
setState(() {});
1 Comment
If you want to execute some code as soon as the widget loaded , you could simply put this code in the initstate like the following ;
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => yourFunction(context));
}
In this way , the yourFunction will be exectued as soon as the first frame of the widget loaded on the screen.
2 Comments
With the latest update, Flutter 3.7, you can directly check whether the widget is mounted using the context. Here's an example use:
@override
Widget build(BuildContext context) {
return OutlinedButton(
onPressed: () async {
await Future<void>.delayed(const Duration(seconds: 1));
if (context.mounted) {
Navigator.of(context).pop();
}
},
child: const Text('Delayed pop'),
);
}
For details, refer to this page.
Comments
I don't think it's currently possible.
Here's the mounted property: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L974
bool get mounted => _element != null;
And here's when _element is set: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L3816
_state._element = this
And I don't see any hook around this code that would inform us.
Why not use initState anyway? It's probably what you want. Here's the comment above the mounted property: https://github.com/flutter/flutter/blob/master/packages/flutter/lib/src/widgets/framework.dart#L967
/// After creating a [State] object and before calling [initState], the
/// framework "mounts" the [State] object by associating it with a
/// [BuildContext]. The [State] object remains mounted until the framework
Comments
I know this answer comes a little bit late but...
Inside your method, you should have something like this:
if(mounted){
setState(() {});
}
This would help, to rebuild the UI only if something changes. I use this myself inside a method, where I fill my list with users from firestore.
The mounted property helps to avoid the error, when you trying to call setState before build.