save an image from assets to the phone storage in Flutter 2.2
we are going to see in this article how to save images from your application assets in a folder in the phone external storage
before we start we need to add this dependencies in our project in pubspec.yaml
i m going to explain later why we need it :
path_provider: ^2.0.2
path: ^1.8.0
and for android we need to add this to AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this to give permission to your application to create folders and files in the phone storage
so now after preparing the app we can head to start coding :
First we will create a function that convert the image from assets to a file
Future<File> getImageFileFromAssets(String path) async {
final byteData = await rootBundle.load('assets/$path');
Directory appDocDir = await getApplicationDocumentsDirectory();
String imagesAppDirectory = appDocDir.path;
final file =
await File('$imagesAppDirectory/$path').create(recursive: true);
await file.writeAsBytes(byteData.buffer
.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));
return file;
}
we have converted the image into byte data
than we used the package path_provider that we have imported to get the path of the app document with getApplicationDocumentsDirectory() function
here : File(‘$imagesAppDirectory/$path’).create(recursive: true); we have created a file on that path
and we wrote the image byte data on the file that we created so like this we convert the image to a file
now we are going to store the image file in the app data in the external storage
we are going to create another function to do this job:
Future<void> saveImageF(String ImagDetails) async {
String imgPath = (imageLinkInAssets).substring(7);
late File image;
await getImageFileFromAssets(imgPath).then((file) => image = file);
final extDir = await getExternalStorageDirectory();
// Path of file in android data files
final myImagePath = '${extDir!.path}/images';
//create the base name
String basename = (ImagDetails).substring(20);
// File copied to ext directory.
File newImage = await image.copy("$myImagePath/${p.basename(basename)}");
print(newImage.path);
}
first we used sub string to get the image path without the assets/ to send it to the first function
than we used our function to getImageFileFromAssets() to get the file of the image
after that we used getExternalStorageDirectory() to get the external storage path of the application
'${extDir!.path}/images';
here we created the image path in the External Storage Directory
String basename = (ImagDetails).substring(20);
here we wanted to get the basename of the image like image1.png to make it as a name for the image file
File newImage = await image.copy("$myImagePath/${p.basename(basename)}");
than the final step to add the image file to the directory and like thiw we have stored the image in the external storage of our application .