Flutter使用sqflite存笔记后无法动态刷新列表,重启才显示如何解决
问题原因
你的主页拉取数据的逻辑setNotesFromDB只在initState生命周期里执行一次,也就是页面首次创建的时候才会拉取数据库数据。你跳转到添加笔记页保存数据后返回主页,主页没有重新执行拉取数据的逻辑,所以看不到最新内容,重启应用相当于重新创建主页,才会触发数据拉取。
修复步骤
1. 监听添加笔记页面返回事件,返回后重新拉取数据
修改MainScreen中 FloatingActionButton 的onPressed逻辑,等待添加页面关闭后重新拉取数据库数据刷新列表:
floatingActionButton: Container( height: 80.0, width: 80.0, child: FittedBox( child: FloatingActionButton( onPressed: () async { // 等待添加笔记页面关闭 await Navigator.push(context, MaterialPageRoute(builder: (context) => AddingNotes())); // 返回后重新拉取数据刷新列表 await setNotesFromDB(); }, child: const Icon( Icons.add, ), backgroundColor: Colors.green, ), ), ),
2. (可选优化)修复Note类id硬编码问题
你当前创建Note的时候手动写死了id为20,而你的数据库id是自增的,手动传固定id会导致后续插入异常,建议修改Note构造方法,让id可选:
class Note { int? id; String title; String body; Note({this.id, required this.title, required this.body}); // 其余方法保持不变 }
添加笔记页创建Note实例的时候无需传id:
Note note = Note(title: title, body: body);
3. (可选更高性能方案)保存后直接返回新笔记数据,避免重复查库
如果不想每次返回都全量查询数据库,可以在保存成功后把新笔记数据带回主页直接更新:
修改添加页保存逻辑:
callBack: () async { String title = headerController.text; String body = bodyController.text; Note note = Note(title: title, body: body); // insert方法返回的是数据库生成的自增id var newId = await dbHelper.insert(note); // 给note赋值数据库返回的id note.id = newId; // 关闭页面的时候把新笔记带回主页 Navigator.pop(context, note); }
修改主页跳转逻辑,接收返回的新笔记:
onPressed: () async { final newNote = await Navigator.push<Note>(context, MaterialPageRoute(builder: (context) => AddingNotes())); if (newNote != null) { setState(() { noteList.add(newNote); }); } },
内容的提问来源于stack exchange,提问作者ghost deathrider
相关产品推荐
相关产品推荐

