Fix Flutter Unhandled Exception: This widget has been unmounted, so the State no longer has a context

Widget unmounted? State no longer available? If you’re seeing these types of errors while using Flutter, don’t worry – you’re not alone!

When you see the error Unhandled Exception: This widget has been unmounted, it means that the widget in question – most likely a StatefulWidget – was removed from the tree before the end of its lifetime. There are a few scenarios in which this can happen:

[ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active.
#0      State.context.<anonymous closure> (package:flutter/src/widgets/framework.dart:909:9)
#1      State.context (package:flutter/src/widgets/framework.dart:915:6)
#2      _SaleOrdersPageState._fetchProducts.<anonymous closure> (package:example/screens/sales/sales_screen.dart:55:9)
#3      _rootRunUnary (dart:async/zone.dart:1436:47)
#4      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
<asynchronous suspension>
  • If you’re using setState() to update a widget and the widget is removed from the tree before the end of the setState() callback, you’ll see this error.
  • If you’re passing a context to a child widget and the child widget is removed from the tree before the parent widget, you’ll see this error.
  • If you’re using a FutureBuilder or StreamBuilder and the Future or Stream completes before the widget is removed from the tree, you’ll see this error.

This issue can be addressed by adding a line of code to check before applying setState method.

if (mounted) { 
  setState (() => _sales = []);
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close