How to save image data to sqflite database in flutter for persistence

3 Min Read

To save image data to a SQLite database in Flutter, you’ll need to convert the image data into a format that can be stored in a database, such as a BASE64 string. You can then store the BASE64 string in a column of a SQLite table and use it to reconstruct the image later.

Here’s an example of how to save an image to a SQLite database using the sqflite library:

Convert the image data to a BASE64 string:

Uint8List imageBytes = ...; // your image data
String base64Image = base64Encode(imageBytes);

Create a table in the database to store the image data:

Future<void> _createTable(Database db) async {
  await db.execute(

Save the BASE64 string to the database:

Future<void> _saveImage(String base64Image) async {
  Database db = await openDatabase(...);
  await db.transaction((txn) async {
    await txn.rawInsert(
      'INSERT INTO images (data) VALUES (?)',
  await db.close();

Load the image from the database:

Future<Uint8List> _loadImage() async {
  Database db = await openDatabase(...);
  List<Map<String, dynamic>> rows = await db.rawQuery('SELECT data FROM images');
  String base64Image = rows[0]['data'];
  await db.close();
  return base64Decode(base64Image);

Use the image data to create an Image widget:

  await _loadImage(),
  fit: BoxFit.cover,

In this example, the _createTable method creates a table in the database to store the image data. The _saveImage method takes the BASE64 string and saves it to the database using a raw SQL INSERT statement. The _loadImage method loads the BASE64 string from the database and converts it back into an Uint8List using the base64Decode method. Finally, the Image.memory constructor is used to create an Image widget from the binary data.

Share this Article
Leave a comment