You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter组件已卸载致State无上下文错误的修复咨询

问题:Flutter Riverpod搜索功能报错且无法正常工作

错误控制台信息

════════ Exception caught by scheduler library ═════════════════════════════════
This widget has been unmounted, so the State no longer has a context (and should be considered defunct).
════════════════════════════════════════════════════════════════════════════════

使用flutter_riverpod实现搜索框功能时,输入搜索内容触发上述错误,且搜索功能失效,相关代码如下:

用户界面代码

搜索输入框部分

TextFormField(
  …
  onChanged: (search) => controller.updateSearch(search),
  onSaved: (search) {
    search == null ? null : controller.updateSearch(search);
  },
),

列表项构建部分

itemBuilder: (context, index) {
 if (mounted) {
    return name.contains(state.search) ? ListTile(title: Text(name)) : Container();
  }

  return Container();
},

控制器代码

class Controller extends StateNotifier<State> {
Controller() : super(State());

void updateSearch(String search) => state = state.copyWith(search: search);

}

final controllerProvider = StateNotifierProvider.autoDispose< Controller, State>((ref) {
  return Controller();
});

状态代码

class State {
  State({this.search = "", this.value = const AsyncValue.data(null)});

  final String search;
  final AsyncValue<void> value;
  bool get isLoading => value.isLoading;

  State copyWith({String? search, AsyncValue<void>? value}) {
    return State(search: search ?? this.search, value: value ?? this.value);
  }
}

请问该如何修复此错误?若需要更多信息可告知,感谢帮助!


内容的提问来源于stack exchange,提问作者My Car

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:31:11