Hi all,
The image is saved in the getApplicationDocumentsDirectory() and I also save the image path in the
shared preferences.
So that I can find the image again. The caching works as long I'm not stopping the App.
If I stop the App and start it again, Flutter is saying the file doesn't exist.
I'm wondering how long the image is cached in the getApplicationDocumentsDirectory and why it is removed?
Is there a better way to cache/store the image to the device for later use?
I've seen a Youtube video by converting the image in base64 and save the converted image as String in the shared preferences.
Is this the best solution?
Below you can see my code
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
SharedPreferences prefs;
File _image;
File _memoryImage;
Future _onPhotoLibraryTapped() async {
// Image Picker plugin
final File image = await ImagePicker.pickImage(
source: ImageSource.gallery, imageQuality: 100);
final Directory directory = await getApplicationDocumentsDirectory();
// Copy the image into the new directory
final File newImage = await image.copy('${directory.path}/profile_image.jpg');
// Save the image path in shared preferences
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setString('profile_image', newImage.path);
// Print the image path
print(newImage.path);
setState(() {
_image = newImage;
});
}
Future _loadImageFromMemory() async {
// Get the image path from shared preferences
SharedPreferences prefs = await SharedPreferences.getInstance();
String imagePath = prefs.getString('profile_image') ?? null;
if(imagePath != null) {
setState(() {
_memoryImage = File(imagePath);
});
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
actions: <Widget>[
IconButton(
icon: Icon(Icons.refresh),
onPressed: () {
_loadImageFromMemory();
},
),
IconButton(
icon: Icon(Icons.add),
onPressed: () {
_onPhotoLibraryTapped();
},
),
],
),
body: Column(
children: <Widget>[
Container(
child: _image == null ? Text('No image selected') : Image.file(_image),
),
Container(
child: _memoryImage == null ? Text('No image in the cache') : Image.file(_memoryImage),
),
],
),
);
}
}
Thank you and Happy New Year!
Marc