imagefile-uploadhiveflutter-hiveflutter-image-picker

How to save image in hive DB picked by user using ImagePicker?


As i implemented my own way to put image in hive but it did not work. I searched on internet but not found any sound solution. A complete code to implement it can be helpful. Any help will be appreciated. Thanks!

Code i used to pick image and put it into hive.

  File? _image;
    Future getAndSaveImage() async {
      final image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image == null) return;
final tempImage = File(image.path);
setState(() {
  _image = tempImage;
  images.put(_nameController.text, ProfileImage(_image!));
});
    }

Hive Model Class

import 'dart:io';

import 'package:hive/hive.dart';

part 'profile_image.g.dart';

@HiveType(typeId: 2)
class ProfileImage {
  ProfileImage(this.profileStudentImage);
  @HiveField(0)
  final File profileStudentImage;
}

Please give a proper working solution i really need it.😢


Solution

  • You first need to convert the image to a format that can be stored in Hive, typically a Uint8List (byte array). Then, you can save this byte array in a Hive box

    Before saving an image to Hive, you need to convert it into a Uint8List. You can use the ImagePicker package to select an image and convert it to bytes.

    PickedFile pickedFile = await ImagePicker().getImage(source: ImageSource.gallery);
    List<int> imageBytes = await pickedFile.readAsBytes();
    Uint8List imageUint8List = Uint8List.fromList(imageBytes);
    

    Save Image to Hive:

    Once you have the image in Uint8List format, you can save it to Hive:

    Box imageBox = Hive.box('images'); // Open the 'images' box
    
    // Save the Uint8List to Hive
    imageBox.put('image_key', imageUint8List);
    

    Retrieve Image from Hive:

    Box imageBox = Hive.box('images'); // Open the 'images' box
    
    // Get the Uint8List from Hive
    Uint8List retrievedImage = imageBox.get('image_key');
    

    Display Image:

    Image.memory(retrievedImage);