Flutter开发如何在另一页面仅抽取展示ListView中未勾选的随机任务
问题修复方案
你只需修改TaskData类中的随机抽取逻辑,先过滤出所有未完成的任务再执行随机抽取即可,同时可增加边界情况处理避免无未完成任务时出现崩溃:
1. 修改rann方法
Future<String> rann() async { // 过滤所有未勾选的未完成任务 final unfinishedTasks = _tasks.where((task) => !task.isDone).toList(); // 无未完成任务时返回提示 if (unfinishedTasks.isEmpty) { return "当前无未完成任务"; } // 对未完成任务列表打乱后取首个 return (unfinishedTasks..shuffle()).first.name; }
2. 可选优化:完善FutureBuilder展示逻辑
你可以调整原FutureBuilder的代码,区分加载状态、异常状态的展示效果,避免页面出现null等异常文本:
Padding( padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 0), child: FutureBuilder( future: Provider.of<TaskData>(context).rann(), builder: (context, snapshot) { // 加载中展示加载动画 if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(color: Colors.white); } return Align( alignment: Alignment.center, child: Text( snapshot.data ?? "抽取出错,请重试", textAlign: TextAlign.center, style: const TextStyle( color: Colors.white, fontSize: 30, fontWeight: FontWeight.w700), ), ); }, ), )
内容的提问来源于stack exchange,提问作者Bn Minki
相关产品推荐
相关产品推荐

