未来<列表<Note>> 不是列表<Note>类型的子类型



我正在从sqlite获取数据,并试图在列表视图中设置它,但我遇到了错误:

type 'Future<List<Note>>' is not a subtype of type 'List<Note>'

这是我的sqlite查询函数:

Future<List<Note>> readAllNotes() async {
final db = await instance.database;
final orderBy = '${NoteFields.timeAdded} ASC';
final result = await db?.query(tableNotes, orderBy: orderBy);
return result!.map((json) => Note.fromJson(json)) as List<Note>;

}

这里是我调用readAllNotes((的地方:

class NoteListWidget extends StatefulWidget {

const NoteListWidget({
Key? key,
}) : super(key: key);
@override
State<NoteListWidget> createState() => _NoteListWidgetState();
}
class _NoteListWidgetState extends State<NoteListWidget> {

@override
Widget build(BuildContext context) {
List<Note> note = NotesDataBase.instance.readAllNotes() as List<Note>;
return ListView.builder(
itemCount: note.toString().characters.length,
itemBuilder: (ctx, index) {
return NoteTileWidget(
body: note[index].body,
title: note[index].title,
timeAdded:
('${note[index].timeAdded.day}/${note[index].timeAdded.month}/${note[index].timeAdded.year}'),
id: note[index].id,
);
});

}}

您必须使用FutureBuilder:

class _NoteListWidgetState extends State<NoteListWidget> {
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Note>>(
future: NotesDataBase.instance.readAllNotes(),
builder: (context, snapshot) {
if (snapshot.hasData){
final List<Note> notes = snapshot.data;
return ListView.builder(
itemCount: notes.length,
itemBuilder: (ctx, index) {
return NoteTileWidget(
body: notes[index].body,
title: notes[index].title,
timeAdded:
('${notes[index].timeAdded.day}/${notes[index].timeAdded.month}/${notes[index].timeAdded.year}'),
id: notes[index].id,
);
});
}else{
return const CircularProgressIndicator();
}

}
);
}
}
class NoteListWidget extends StatefulWidget {
const NoteListWidget({
Key? key,
}) : super(key: key);
@override
State<NoteListWidget> createState() => _NoteListWidgetState();
}
class _NoteListWidgetState extends State<NoteListWidget> {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: NotesDataBase.instance.readAllNotes(),
builder: (context, dataSnapshot) {
if (dataSnapshot.connectionState == ConnectionState.waiting) {
return const Center(
child: CircularProgressIndicator(),
);
} else {
return ListView.builder(
itemCount: (dataSnapshot.data as List).length,
itemBuilder: (ctx, index) {
final note = (dataSnapshot.data as List)[index];
return NoteTileWidget(
body: note[index].body,
title: note[index].title,
timeAdded:
('${note[index].timeAdded.day}/${note[index].timeAdded.month}/${note[index].timeAdded.year}'),
id: note[index].id,
);
});
}
});
}
}

最新更新