I’m trying to retrieve data from a database, and have made these two methods inside of a certain "TodoDB" class:
Future<List<SurveyData>> fetchAll() async {
final database = await DatabaseService().database;
final survey = await database.rawQuery('''SELECT * from $tableName''');
return survey.map((survey) => SurveyData.fromSqfliteDatabase(survey)).toList();
}
Future<SurveyData> fetchById(int id) async {
final database = await DatabaseService().database;
final survey = await database.rawQuery('''SELECT * from $tableName WHERE id = ?''', [id]);
return SurveyData.fromSqfliteDatabase(survey.first);
}
later on, I call the upper methods in this other class:
class SurveyUtilities {
final todoDB = TodoDB();
/// function that retrieves and parses all surveys data from database *
Future<List<SurveyData>> getSurveys() async {
return todoDB.fetchAll();
}
/// function that retrieves and parses a certain survey data from database *
Future<SurveyData> getSurveyData(int id) async {
return todoDB.fetchById(id);
}
}
I tried a bunch of solutions online, but I always get this error message:
"type ‘Future<List>’ is not a subtype of type ‘List’ in type cast".
I’ve also tried writing the getSurveys() method like this:
Future<List<SurveyData>> getSurveys() async {
final allSurveys = await todoDB.fetchAll();
return allSurveys;
}
but the result is always the same.
I haven’t worked with dart, databases or sql before, so I apologize if there’s some obvious mistakes (I’m still learning!)
For context, my SurveyDaya is formatted as follows:
SurveyData({required this.id, required this.title, required this.description, required this.questions});
factory SurveyData.fromSqfliteDatabase(Map<String, dynamic> map) => SurveyData(
id: map['id']?.toInt() ?? 0,
title: map['title'] ?? '',
description: map['description'] ?? '',
questions: map['questions'] ?? '',
);
2
Answers
You should update SurveyUtilities class like this, it will solve issue
You should remove the "Future" from the return type of the
getSurveys
function because it is unnecessary. The updated method will be like this:And wherever you are calling this function to initialize the list for UI will be used liked this: