I am getting the data from sqlite and trying to set it in a List view but I am getting error:
type 'Future<List<Note>>' is not a subtype of type 'List<Note>'
Here is my sqlite query function:
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>;
}
And here is where am calling readAllNotes():
class NoteListWidget extends StatefulWidget {
const NoteListWidget({
Key? key,
}) : super(key: key);
@override
State<NoteListWidget> createState() => _NoteListWidgetState();
}
class _NoteListWidgetState extends State<NoteListWidget> {
// late Future<List<Note>> note;
@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,
);
});
} }
CodePudding user response:
You have to await for the result. Change this line:
List<Note> note = NotesDataBase.instance.readAllNotes() as List<Note>;
to
List<Note> note = await NotesDataBase.instance.readAllNotes();
CodePudding user response:
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,
);
});
}
});
}
}
