Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NoSuchMethodError: The method 'markNeedsBuild' was called on null

Tags:

flutter

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?

like image 699
Ray Li Avatar asked Dec 30 '22 22:12

Ray Li


1 Answers

'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;
        });
    }
});
like image 200
Ray Li Avatar answered Jan 02 '23 13:01

Ray Li