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
相关产品推荐
相关产品推荐

