我们如何将图像存储在共享偏好中,并在flutter中从共享偏好中检索?
您可以将Image转换为Unit8List,然后将UnitList8转换为base64并保存。
static Future<bool> saveImage(List<int> imageBytes) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
String base64Image = base64Encode(imageBytes);
return prefs.setString("image", base64Image);
}
static Future<Image> getImage() async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
Uint8List bytes = base64Decode(prefs.getString("image"));
return Image.memory(bytes);
}
然后使用它。
来自资产
ByteData bytes = await rootBundle.load('assets/file');
SharedPreferencesHelper.saveImage(bytes.buffer.asUint8List());
来自网络
http.Response response = await http.get(
'https://flutter.io/images/flutter-mark-square-100.png',
);
if(response.statusCode == 200){
SharedPreferencesHelper.saveImage(response.bodyBytes);
}else{
//TODO: Handle error
}
我并不完全知道具有共享偏好的解决方案,但我是用path_provider这样做的;
用于保存到磁盘;
Future<bool> saveNetworkImageToDisk() async{
await fileController.prepareInSubDirectoryJsonFile();
try{
var response=await get(this.imageUrl); //http package for geting image from the internet
if(response.statusCode==200){
await fileController.file.writeAsBytes(response.bodyBytes);
return true;
}else{
return false;
}
}catch(e){
return false;
}
}
用于从磁盘获取;
Future<File> getImage() async{
Future<File> getImage() async{
await fileController.prepareInSubDirectoryJsonFile();
return fileController.file;
}
在file_controller.dart prepareJsonFileFunction中执行此操作:你需要正义;
import 'dart:io';
import 'package:path_provider/path_provider.dart';
String directory=await getApplicationDocumentsDirectory().then((appDirectory){return appDirectory;});
String appPath=directory.path;
file=File('${this.appPath}/${this.fileName}');
我也在try-catch系统中做这项工作,所以你可以修改它们:(