Reputation: 451
I want to store the image as a base64 string in Sqlite in Flutter, and then decode that base64 into image and display it. Here is my utility code that has functions of encoding and decoding base64:
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'dart:convert';
class Utility {
static Image imageFromBase64String(String base64String) {
return Image.memory(
base64Decode(base64String),
fit: BoxFit.fill,
);
}
static Uint8List dataFromBase64String(String base64String) {
return base64Decode(base64String);
}
static String base64String(Uint8List data) {
return base64Encode(data);
}
}
Now I have this function that should pick the image with Image Picker from gallery, and then encode it to base64, but I am getting an error:
_getImage() {
picker.getImage(source: ImageSource.gallery).then((imgFile) {
String imgString = Utility.base64String(imgFile.readAsBytes());
});
}
The error:
The argument type 'Future<Uint8List>' can't be assigned to the parameter type 'Uint8List'.
After that would be stored in Sqlite (this is obviously not full code), I would then just decode it in a list tile or whatever like this:
Utility.imageFromBase64String(employee.photo);
What am I doing wrong, and also, if you guys know a good and clean way to store the base64 string and then decode it in Sqlite in Flutter, let me know. Thank you!
EDIT
When I add readAsBytesSync
I'm getting this error instead, not sure what the issue is:
The method 'readAsBytesSync' isn't defined for the type 'PickedFile'. Try correcting the name to the name of an existing method, or defining a method named 'readAsBytesSync'.
Upvotes: 2
Views: 1506
Reputation: 107231
If you check the File class documentation. You can see that readAsBytes
function returns Future<Uint8List>
, that's why you are getting that error. To fix this issue, you have to use readAsBytesSync
which returns Uint8List
.
Replace:
String imgString = Utility.base64String(imgFile.readAsBytes());
with:
String imgString = Utility.base64String(imgFile.readAsBytesSync());
The image picker uses a class called PickedFile to provide the file details bac, which doesn't support readAsBytesSync
. So you can use:
final file = File(imgFile.path);
String imgString = Utility.base64String(file.readAsBytesSync());
Upvotes: 3