1

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.😢

1
  • you may also consider saving images on the localStorage of the app and saving that path on db instead of converting in some format and then saving directly on db. Commented Dec 15, 2024 at 18:37

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Though the modal class was not defining Unit8List despite importing the typed package, I declared the variable as dynamic and it worked perfectly fine. Thanks a lot, man!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.