How can we store image in shared preferences and retrieve from shared preferences in flutter?
Asked
Active
Viewed 4,772 times
0
-
https://stackoverflow.com/questions/51338041/how-to-save-image-file-in-flutter-file-selected-using-image-picker-plugin Give this a try – xahid_rocks Mar 31 '21 at 04:31
-
Does this answer your question? [How to Save Image File in Flutter ? File selected using Image\_picker plugin](https://stackoverflow.com/questions/51338041/how-to-save-image-file-in-flutter-file-selected-using-image-picker-plugin) – Taba Mar 31 '21 at 18:04
2 Answers
10
You can convert the Image to Unit8List then convert UnitList8 to base64 and save it. Here is an example.
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);
}
Then use it.
From Assets
ByteData bytes = await rootBundle.load('assets/file');
SharedPreferencesHelper.saveImage(bytes.buffer.asUint8List());
From Network
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
}

Abhi Tripathi
- 526
- 2
- 10
0
I am not exactly know the solution with shared preferences but I was doing that with path_provider like just this;
for saving to disk;
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;
}
}
for getting from disk;
Future<File> getImage() async{
Future<File> getImage() async{
await fileController.prepareInSubDirectoryJsonFile();
return fileController.file;
}
in file_controller.dart prepareJsonFileFunction doing this: you need just;
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}');
Also I am doing this works in try-catch system, so you can modify them :)

leylekseven
- 687
- 7
- 15