skip to Main Content

I have a form(title, description, images, etc…), in this form I pick multiple images and store them in a list, I want to insert this list of images in the database and also fetchAndSet the data later on. since we can’t store a list in a table of the database, I encoded my list using JSON, and then I stored them in the database. in the fetchAndSet function, I decode them but I don’t see any result.

here is my db_helper.dart File,

import 'dart:convert';
import 'dart:ffi';

import 'package:sqflite/sqflite.dart' as sql;
import 'package:path/path.dart' as path;
import 'package:sqflite/sqlite_api.dart';

class DbHelper {
  static Future<Database> database() async {
    final dbpath = await sql.getDatabasesPath();
    final sqlDb = await sql.openDatabase(path.join(dbpath, 'places.db'),
        onCreate: (db, version) {
      db.execute(
        'CREATE TABLE user_places(id TEXT PRIMARY KEY,name TEXT,images TEXT,description TEXT,regDate TEXT,travelDate Text,location Text,imageCover Text)',
      );
    }, version: 1);
    return sqlDb;
  }

  Future<void> insert(String table, Map<String, Object> data) async {
    final db = await DbHelper.database();
    db.insert(
      table,
      data,
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  static Future<List<Map<String, dynamic>>> getPlace(String table) async {
    final db = await database();
    return db.query(table);
  }
}

And this is my model,

import 'dart:io';
import 'package:flutter/material.dart';

class PlaceLocation {
  final double latitude;
  final double longitude;
  final String? address;
  PlaceLocation({
    required this.latitude,
    required this.longitude,
    this.address,
  });
}

class Travel {
  final String id;
  final String name;
  final File imageCover;
  final List<dynamic> imageList;
  final PlaceLocation? location;
  final String description;
  final DateTime regDate;
  final DateTime travelDate;

  Travel({
    required this.id,
    required this.name,
    required this.imageCover,
    required this.location,
    required this.description,
    required this.imageList,
    required this.regDate,
    required this.travelDate,
  });
}

And this is the Add Function (i encode the list in here!!)

Future<void> addTravel(
      {required String pickedname,
      required String pickedescription,
      required File pickedCoverImage,
      required List<File> imageList,
      required DateTime travelDate}) async {
    final uuid = Uuid();
    final pickedId = uuid.v4();
    final newTravel = Travel(
        id: pickedId,
        name: pickedname,
        imageCover: pickedCoverImage,
        location: null,
        description: pickedescription,
        imageList: imageList,
        regDate: DateTime.now(),
        travelDate: travelDate);
    _items.add(newTravel);
    notifyListeners();
    for (File image in imageList) {
      List<int> bytes = await image.readAsBytes();
      String encoded = base64Encode(bytes);
      encodedImages.add(encoded);
      DbHelper().insert('user_places', {
        'id': newTravel.id,
        'name': newTravel.name,
        'images': json.encode(encodedImages),
        'description': newTravel.description,
        'regDate': newTravel.regDate.toIso8601String(),
        'travelDate': newTravel.travelDate.toIso8601String(),
        'location': newTravel.location!,
        'imageCover': newTravel.imageCover.path
      });
    }
  }

3

Answers


  1. Chosen as BEST ANSWER

    thank you guys, I found the error, and here is the updated code for fetchAndSet function:

     Future<void> fetchAndSet() async {
    //stores the table in dataList
    final dataList = await DbHelper.getPlace('user_places');
    final firstPlace = dataList.first;
    final imageJson = firstPlace['imagesList'];
    final imagesList =
        (imageJson != null) ? json.decode(imageJson) as List<dynamic> : [];
    final places = dataList.map((e) {
      final List<dynamic> imagesBytesList = (e['imagesList'] != null)
          ? (jsonDecode(e['imagesList']) as List<dynamic>)
              .map((image) => base64.decode(image))
              .toList()
          : [];
    
      final List<dynamic> imageList = [];
    
      for (var i = 0; i < imagesBytesList.length; i++) {
        final image = imagesBytesList[i];
        if (image is Uint8List) {
          imageList.add(File.fromRawPath(image));
        } else if (image is String) {
          imageList.add(image);
        }
      }
      return Travel(
        id: e['id'],
        name: e['name'],
        imageCover: File(e['imageCover']),
        location: null,
        description: e['description'],
        imageList: imageList,
        regDate: DateTime.parse(e['regDate']),
        travelDate: DateTime.parse(e['travelDate']),
      );
    }).toList();
    if (kDebugMode) {
      print('Control step reached: $places');
    }
    
    _items = places;
    notifyListeners();
    

    }


  2. Sure, here is an example of how you can encode and decode a list of images to/from JSON format in Flutter using the dart:convert library:

    import 'dart:convert';
    
    // Encode the list of images to JSON
    List<String> images = ['image1.jpg', 'image2.jpg', 'image3.jpg'];
    String encodedImages = jsonEncode(images);
    
    // Store the encoded JSON data in the database
    // ...
    
    // Fetch the encoded JSON data from the database
    String fetchedEncodedImages = ''; // assume this is fetched from the database
    
    // Decode the JSON data back to a list of images
    List<dynamic> decodedImages = jsonDecode(fetchedEncodedImages);
    List<String> fetchedImages = List<String>.from(decodedImages);
    
    // Use the fetched images as needed
    // ...
    

    In this example, we use the jsonEncode() function to convert the list
    of images to a JSON-encoded string, and the jsonDecode() function to
    decode the fetched JSON-encoded string back to a list of images. We
    assume that the encoded JSON data is stored in the
    fetchedEncodedImages variable and fetched from the database using your
    preferred method. Finally, we use the List.from() constructor to
    convert the decoded JSON data to a List type for use in our
    Flutter app.

    Login or Signup to reply.
  3. You have for loop, and for each image in imageList, you call the insert function.
    You will insert a row on the first call and update it for each image in the list.
    You need to call insert only one time, after you prepare your encodedImages list.

    Also, you need to check the size of this list. The text field is big, but not unlimited. If your images are not very small, maybe you should save them on the file system and save image paths to DB.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search