The widget was removed before an async task finished. Check mounted before calling setState, and cancel timers, listeners and subscriptions in dispose().
class _ProfileState extends State<Profile> {
String? name;
late final StreamSubscription sub;
@override
void initState() {
super.initState();
sub = userStream.listen((u) {
if (!mounted) return;
setState(() => name = u.name);
});
}
Future<void> load() async {
final user = await api.fetchUser();
if (!mounted) return; // the user may have left the screen
setState(() => name = user.name);
}
@override
void dispose() {
sub.cancel(); // stop callbacks reaching a dead widget
super.dispose();
}
}The mounted check silences the symptom, while cancelling in dispose() fixes the cause for long-lived sources like streams and timers. For state that should survive screen changes, move it out of the widget into a state management solution.
