Issue
I am trying to save image in sqlite database using flutter below is my helper class where i want to save data
class DBHelper{
static Database? _db;
static const String ID = 'id';
static const String NAME = 'photo_name';
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<SaveImage> save(SaveImage employee) async {
var dbClient = await db;
employee.id = await dbClient.insert(TABLE, employee.toMap());
return employee;
}
Future<List<SaveImage>> getPhotos() async {
var dbClient = await db;
List<Map> maps = await dbClient.query(TABLE, columns: [ID, NAME]);
List<SaveImage> employees = [];
if (maps.length > 0) {
for (int i = 0; i < maps.length; i++) {
employees.add(SaveImage.fromMap(maps[i]));
}
}
return employees;
}
Future close() async {
var dbClient = await db;
dbClient.close();
}
}
I have used image picker to pick image from gallery converted into base 64 string and save it in db.
selectImages() async {
final List<XFile>? selectedImages = await _picker.pickMultiImage();
if (selectedImages!.isNotEmpty) {
_imageList.addAll(selectedImages);
}
for (var i = 0; i > _imageList.length; i++) {
try {
var bytes = Io.File(_imageList[i].path).readAsBytesSync();
String img64 = base64Encode(bytes);
SaveImage saveImage = SaveImage(id: i, image: img64);
dbHelper.save(saveImage);
} catch (e) {
print(e);
}
}
print("selected images are " + _imageList.length.toString());
if (images.isEmpty) {
print("no data");
} else {
print("data");
}
}
heres my init state method and a method to retrieve data from db
@override
void initState() {
// TODO: implement initState
super.initState();
dbHelper = DBHelper();
images = [];
refreshImages();
print("length of image is " + images.length.toString());
}
refreshImages() async {
await dbHelper.getPhotos().then((value) {
images.addAll(value);
});
}
i cant save image in db please help me
Solution
I think you are missing some parts in your configuration:
_onCreate(Database db, int version) async {
await db.execute("CREATE TABLE $TABLE ($ID INTEGER, $NAME TEXT)");
}
should be
Future<void> _onCreate(Database db, int version) async {
await db.execute('CREATE TABLE $TABLE ('
'$ID INTEGER PRIMARY KEY AUTOINCREMENT, '
'$NAME TEXT)');
}
Full working example:
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
final dbHelper = DBHelper();
await dbHelper.initDb();
final bob = await dbHelper.save(Employee(name: 'Bob'));
final john = await dbHelper.save(Employee(name: 'John'));
final employees = await dbHelper.getEmployees();
print(bob);
print(john);
print(employees);
runApp(const MaterialApp(home: Text('app')));
}
class Employee {
const Employee({
this.id,
required this.name,
});
factory Employee.fromMap(Map<String, dynamic> map) {
final id = map['id'];
final name = map['name'];
if (name is! String) {
throw Exception('Employee name from database must be a String');
}
if (id is! int?) {
throw Exception('Employee id from database must be an integer');
}
return Employee(id: id, name: name);
}
final int? id;
final String name;
Employee copyWith({
int? id,
String? name,
}) {
return Employee(
id: id ?? this.id,
name: name ?? this.name,
);
}
Map<String, dynamic> toMap() => {'id': id, 'name': name};
@override
String toString() {
return toMap().toString();
}
}
class DBHelper {
static Database? _db;
static const String ID = 'id';
static const String NAME = 'name';
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!;
}
Future<Database> initDb() async {
final documentsDirectory = await getApplicationDocumentsDirectory();
final path = '$documentsDirectory${Platform.pathSeparator}$DB_NAME';
return openDatabase(path, version: 1, onCreate: _onCreate);
}
Future<void> _onCreate(Database db, int version) async {
await db.execute('CREATE TABLE $TABLE ('
'$ID INTEGER PRIMARY KEY AUTOINCREMENT, '
'$NAME TEXT)');
}
Future<Employee> save(Employee employee) async {
final dbClient = await db;
final id = await dbClient.insert(TABLE, employee.toMap());
return employee.copyWith(id: id);
}
Future<List<Employee>> getEmployees() async {
final dbClient = await db;
final maps = await dbClient.query(TABLE, columns: [ID, NAME]);
final employees = <Employee>[];
if (maps.isNotEmpty) {
for (int i = 0; i < maps.length; i++) {
employees.add(Employee.fromMap(maps[i]));
}
}
return employees;
}
Future close() async {
final dbClient = await db;
dbClient.close();
}
}
Answered By - Wim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.