Flutter Save Images as String in SQLite Database
Welcome to my next Flutter article about image saving in SQLite DB as a String. There have many ways to pick an image from the gallery and save it in your application for further use. Here I show you how we can encode an image as a String and decode it. Also, I want to say that this is a common use case in mobile applications. Let’s see how we can do it using the Flutter app development framework. Here I plan to show you how to pick an image from the gallery and save it in the SQLite Database as a string after encoding it, and finally, how to decode it and show it in a list view. Here the most useful parts are how to encode the image to a String and How to decode it into an image. Here we go !!!
Adding Dependencies
First, you must add the following dependencies to your pubspec.yaml.
sqflite: ^2.0.3
path_provider: ^2.0.11
async:io: ^1.0.3
shared_preferences: ^2.0.15
image_picker: ^0.8.5+3
Creating the Model
Create the model class called photo, which is used to upload and retrieve an image.
class photo {
late int? id = 0;
late String? photoName = "";
photo(int i, String imgString){
this.photoName = imgString;
}
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'];
}
}
Creating the Database Helper Class
Here I am trying to save the image in SQLite DB. So we need to create a database helper class. Here include all the methods for saving and fetching the details from SQLite DB.
import 'dart:async';
import 'dart:io';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_application_image/model/photo.dart';
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{
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;
print(photo.photoName);
photo.id = await dbClient!.insert(TABLE, photo.toMap());
print(photo.id);
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.isNotEmpty){
for(int i = 0; i < maps.length; i++){
photos.add(photo.fromMap(Map<String, dynamic>.from(maps[i])));
}
}
print("photos {{$photos}}");
return photos;
}
Future close() async {
var dbClient = await db;
dbClient!.close();
}
}
Pick up and Encode the Image.
The following method is used to get images from the gallery and save them in the SQLite database as String.
pickImageFromGallery() {
ImagePicker().pickImage(source: ImageSource.gallery).then((imgFile) async {
String imgString = Utility.base64String(await imgFile!.readAsBytes());
print(imgString);
photo photo1 = photo(0, imgString);
dbHelper.save(photo1);
refreshImages();
});
}
Decode and Showing the Image
gridView(){
return Padding(
padding: EdgeInsets.all(5.0),
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: 1.0,
mainAxisSpacing: 4.0,
crossAxisSpacing: 4.0,
children: images.map((photo) {
print("photo name");
print(photo.photoName);
return Utility.imageFromBase64String(photo.photoName ?? "");
}).toList(),
),
);
}
Utility Class for Encoding and Decoding the Image
Here is the utility class used to encode and decode image data.
import 'dart:typed_data';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
class Utility {
static Image imageFromBase64String(String base64String) {
return Image.memory(
base64Decode(base64String),
fit: BoxFit.fill,
);
}
static Uint8List dataFromBase64String(String base64String) {
return base64Decode(base64String);
}
static String base64String(Uint8List data) {
return base64Encode(data);
}
}
I think this article was helpful for you to have a piece of knowledge on how to save images as String in SQLite database. You can find the complete code by clicking the following link.
Happy Coding !!!!
Found this post helpful? Kindly tap the 👏 button below! :)