如何在Flutter Riverpod的StateNotifier类中监听两个列表?
解决方法
要同时监听两个列表,你需要把StateNotifier的状态从单一List<String>改成一个包含两个列表的自定义状态类,统一管理并监听两个列表的变化。
步骤1:定义自定义状态类
先创建一个类封装需要管理的两个列表:
// 自定义状态类,包含要监听的两个列表 class QuestionPaperState { final List<String> imgUrls; final List<String> stackoverflow; QuestionPaperState({ required this.imgUrls, required this.stackoverflow, }); // 复制状态并修改指定属性,保证状态不可变 QuestionPaperState copyWith({ List<String>? imgUrls, List<String>? stackoverflow, }) { return QuestionPaperState( imgUrls: imgUrls ?? this.imgUrls, stackoverflow: stackoverflow ?? this.stackoverflow, ); } }
步骤2:修改StateNotifier类
把原控制器改成基于自定义状态类的实现,同时添加操作stackoverflow列表的方法:
class QuestionPaperController extends StateNotifier<QuestionPaperState> { QuestionPaperController() : super(QuestionPaperState(imgUrls: [], stackoverflow: [])); Future<void> getAllPapers(WidgetRef ref) async { List<String> imgName = ["biology", "chemistry", "maths", "physics"]; try { for (var img in imgName) { final imgUrl = await ref.read(firebaseStorageProvider).getImage(img); // 用copyWith更新imgUrls列表 state = state.copyWith( imgUrls: [...state.imgUrls, imgUrl!], ); } } catch (e) { print(e); } } // 给stackoverflow列表添加元素的方法 void addToStackoverflow(String item) { state = state.copyWith( stackoverflow: [...state.stackoverflow, item], ); } // 清空stackoverflow列表的方法 void clearStackoverflow() { state = state.copyWith(stackoverflow: []); } }
步骤3:更新Provider定义
把Provider的泛型改成自定义状态类:
final questionPaperControllerProvider = StateNotifierProvider<QuestionPaperController, QuestionPaperState>((ref) { return QuestionPaperController(); });
步骤4:在UI中监听两个列表
在Widget里可以分别监听两个列表的变化:
// 监听imgUrls列表 final imgUrls = ref.watch(questionPaperControllerProvider.select((state) => state.imgUrls)); // 监听stackoverflow列表 final stackoverflowList = ref.watch(questionPaperControllerProvider.select((state) => state.stackoverflow));
这样就能同时对两个列表进行状态管理和监听,所有状态更新都通过copyWith保持不可变性,符合StateNotifier的使用规范。
内容的提问来源于stack exchange,提问作者Fatih Yılmaz
相关产品推荐
相关产品推荐

