I am building an app where the user is able to store favorites locally on their device. Therefor I am using the SQFlite package.
Opening the Favorite page I am running the following error:
Exception has occurred. _CastError (type 'Null' is not a subtype of type 'String' in type cast)
This is my model class:
class Model {
late String name;
late String description;
final String imagePath;
late int id;
Model({
required this.name,
required this.id,
required this.description,
required this.imagePath,
});
Map<String, dynamic> toMap() {
return {
'id': id,
'name': name,
'imagePath': imagePath,
'description': description,
};
}
}
And here where the exception occurs:
Future<List<Model>> getMechanism() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('fav');
return List.generate(maps.length, (i) {
return Model(
id: maps[i]['id'],
name: maps[i]['name'] as String,
imagePath: maps[i]['imagePath'] as String,
description: maps[i]['description'] as String,
);
});
}
Printing the map variable I receive the following:
flutter: [{id: 1, name: Model, imagePath: null, description: null}]
This is the model class:
List<Model> model = <Model>[
Model(
name: 'Test',
id: 1,
imagePath: 'assets/images/model.png',
description: 'description'
),
Edit:
The function adding the items to the favorites database:
Future initDb() async {
database = openDatabase(
join(await getDatabasesPath(), 'fav'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE fav(id INTEGER PRIMARY KEY, name TEXT, imagePath TEXT, description TEXT)");
},
version: 1,
);
}
Future<void> insertEntry(Model model) async {
final Database db = await database;
await db.insert(
'fav',
model.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
There are no errors found in your code.
You may please check the maps
variable with print or log, to see whether the data is valid or not.