我在从共享首选项中获取图像时遇到以下问题。图像存在,但我得到的只是空白的十字图标。我尝试了其他方法,但每次尝试都只得到空白十字图标。我正在从画廊或相机获取图像。
void takePhoto(ImageSource source) async {
final image = await _picker.getImage(
source: source,
);
if (image!= null) {
final imageTemporary = File(image.path);
setState(() =>
this.image = imageTemporary);
final bytes = await image.readAsBytes();
final base64Image = base64Encode(bytes);
print(base64Image);
await prefs?.setString('myImageKey', base64Image);
}
}
Future<File?> showData() async{
setState(() {
final base64Image = prefs?.getString('myImageKey');
if (base64Image != null) {
final bytes = base64Decode(base64Image);
this.imageFile = File.fromRawPath(bytes);
}
});
return this.imageFile;
}
Getting image here
Container(
height: 300,
width: 300,
child:
FutureBuilder<File?>(
future: showData(),
builder: (context, snapshot) {
if (snapshot.hasData) {
print("image selected");
return
Image.file(snapshot.data!);
} else {
return Text("No images selected");
}
},
),
)
看起来问题可能与您如何从 base64 字符串解码图像有关。而不是使用 File.fromRawPath(bytes),你应该尝试使用 File.fromRawPath(Uint8List.fromList(bytes)).
以下是您的 showData 函数在更新代码后的样子:
Future<File?> showData() async {
final base64Image = prefs?.getString('myImageKey');
if (base64Image != null) {
final bytes = base64Decode(base64Image);
final imageFile = File.fromRawPath(Uint8List.fromList(bytes));
return imageFile;
} else {
return null;
}
}
此外,通过在设置后检查 base64Image 的值,确保图像实际保存到共享首选项中。您可以通过将值打印到控制台或使用调试器来执行此操作。
如果图像未正确保存到共享首选项,您可能需要检查 base64Image 字符串以确保其有效。您可以使用 base64 解码器解码字符串并验证生成的数据是否为图像。