A NoSuchMethodError: The method 'markNeedsBuild' was called on null.
error appears in error logs. I've never seen this error in debugging and users are not reporting any issues. Why does this error occur and is there anything I can do to prevent it from occuring?
'NoSuchMethodError: The method 'markNeedsBuild' was called on null.'
is caused by calling setState()
after a widget is disposed.
Most commonly, this happens when an async network operation completes and tries to update the widget but the widget has already been disposed.
Example:
await networkProvider.getData().then((value) {
// Update data.
setState(() {
data = value;
});
});
To avoid updating widgets after they are disposed, check to ensure the widget still exists before calling setState
. Here's an updated version of the example above that prevents NoSuchMethodError
.
await networkProvider.getData().then((value) {
// Check if widget still exists.
if (mounted) {
// Update data.
setState(() {
data = value;
});
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With