I am trying to store the image in SQFLite database as string. While setting up the DBHelper class, I am getting the said error.
Here is the code of model.dart
and dbhelper.dart
class Photo {
int? id;
String? photoName;
Photo({this.id, this.photoName});
Map<String, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photoName': photoName,
};
return map;
}
Photo.fromMap(Map<String, dynamic> map) {
id = map['id'];
photoName = map['photoName'];
}
}
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'model.dart';
import 'dart:io' as io;
import 'dart:async';
class DBHelper {
static Database? _db;
static const String ID = 'id';
static const String NAME = 'photoName';
static const String TABLE = 'PhotosTable';
static const String DB_NAME = 'photos.db';
Future<Database?> get db async {
if (null != _db) {
return _db;
}
_db = await initDb();
return _db;
}
initDb() async {
io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, DB_NAME);
var db = await openDatabase(path, version: 1, onCreate: _onCreate);
return db;
}
_onCreate(Database db, int version) async {
await db.execute("CREATE TABLE $TABLE ($ID INTEGER, $NAME TEXT)");
}
Future<Photo> save(Photo photo) async {
var dbClient = await db;
photo.id = await dbClient!.insert(TABLE, photo.toMap());
return photo;
}
Future<List<Photo>> getPhotos() async {
var dbClient = await db;
List<Map> maps = await dbClient!.query(TABLE, columns: [ID, NAME]);
List<Photo> photos = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i ) {
photos.add(Photo.fromMap(maps[i])); // ==> Here, at maps[i], it shows the error
}
}
return photos;
}
Future close() async {
var dbClient = await db;
dbClient!.close();
}
}
How can I solve this ?
CodePudding user response:
Change your Photo model to Map<dynamic, dynamic>. The reason for this is that the db is returning a Map<dynamic, dynamic>.
class Photo {
int? id;
String? photoName;
Photo({this.id, this.photoName});
Map<dynamic, dynamic> toMap() {
var map = <String, dynamic>{
'id': id,
'photoName': photoName,
};
return map;
}
Photo.fromMap(Map<dynamic, dynamic> map) {
id = map['id'];
photoName = map['photoName'];
}
}