我想将图像存储在应用程序的localDB中,并使用Hive。但是,我找不到任何例子,我们可以使用Uint8List本地存储一个文件和Hive。我可以使用Hive来持久化原始数据类型,如String、int等,但是不能使用Hive以字节存储任何类似于图像等的东西,尽管它承诺这样做。我找不到同样的例子。
发布于 2022-05-21 09:59:35
不要。将图像保存为磁盘中的文件并将其名称存储到数据库中。
发布于 2022-09-11 12:51:08
//Variables
List? image = [];
List? pickedImages;
List imagesAsBytes = [];//List of images converted to bytes
ImagesToSend imageObj = ImagesToSend(); //New instance of my HiveObject
//Picking images
Future pickImage() async {
setState(() {});
final pickedImages = await ImagePicker().pickMultiImage();
//You can change .pickMultiImage() to pickImage(source: ImageSource.camera) if you want it direct from the camera or pickImage(source: ImageSource.gallery) if you want from the the gallery
if (pickedImages == null) return;
image!.addAll(pickedImages);
setState(() => this.image = image);
//Saving in Hive
if (image == null) return;
imagesAsBytes = [];
for (var i in image!) {
File file = File(i.path);
imagesAsBytes.add(file.readAsBytesSync());
}
imageObj.images = imagesAsBytes;
boxImg.put('images_box', imageObj);
this.imagesAsBytes = boxImg.get('images_box').images;
}
//###############################################################
//My Model
//This is a Hive object that holds the images
//I have this as a different dart file, hopefully, you know what this is
@HiveType(typeId: 0)
class ImagesToSend extends HiveObject {
@HiveField(0)
List<Uint8List>? images;
}
//############################################################
//Don't forget to have the hive adapter and the box open on your main dart file
void main(List<String> args) async {
await Hive.initFlutter();
Hive.registerAdapter(ImagesToSendAdapter());
boxImg = await Hive.openBox<ImagesToSend>('images_box');
runApp(const MyApp());
}
这是我的解决方案,但我仍然面临着一些问题。图片正在显示,但如果我关闭应用程序,蜂巢将仍然持有他们,但它不再显示他们了!如果你能弄清楚这部分,让我知道...lol
https://stackoverflow.com/questions/72328247
复制相似问题