[Flutter/dart]Save the image in a local directory
Overview
In the smartphone application, if you want to retain the data even after the application is closed, get the value of the variable in shared preference etc. So what if you want to save an image?
The conclusion is to save the image in the local directory of the smartphone and save the file path as a String in shared preference etc.
Method
Import the required modules
import 'dart:io' as io;
import 'package:path/path.dart' as path;
First of all, get the image from the gallery of the smartphone (this is the work of getting the image file, whether it is taken with a camera or downloaded from the net)
final picker=ImagePicker();
final pickedFile = await picker.getImage(source: ImageSource.gallery);
String filePath=pickedFile.path;
Next, save the acquired image in the local directory.
io.File _target_file = io.File(filePath); //convert type
String _base_name = path.basename(file); //get file name from the path
String loacl_dir = await getLocalDir(); //get local directory
String _image_path_str = "${loacl_dir}/${_base_name}";
//path to local directory
io.File _image_path_save = io.File(_image_path_str); //convert type
io.File savedFile =
await _image_path_save.writeAsBytes(await_target_file.readAsBytes());
//write file
The third line gets the path to the folder in the local directory, and the fourth line combines the file name and the directory name to create the file path to the local directory.
The function to get the folder path of the local directory is as follows.
static Future<String> getLocalDir() async {
final directory = await getApplicationDocumentsDirectory();
return directory.path;
}
After that, save _image_path_str in shared preference etc.
The method for reading the image is as follows.
_image_file_name=path.basename(_image_path_str);
final String _local_dir= await getLocalDir();
io.File _image_path = io.File("${_local_dir}/${_image_file_name}");
What you have to be careful about here is to read _image_path_str and
io.File _image_path = io.File(_image_path_str);
does not go well. You have to get the local directory each time. (I'm not sure why)
Lastly
If it is an application that connects to a remote server, you can save it on the server, so there may not be much demand ...
However, if you don't want to prepare a server or create a user account just for this, try using it.
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Comments