Writing files to external storage in Flutter
Flutter provides the Path Provider package that helps in accessing the device’s external storage and manipulating files. Follow the steps below to write a file to external storage:
- Add path_provider package dependency to your pubspec.yaml file:
- Import the necessary packages in your Dart file:
- Create a function to write the file:
- Call the function to write the file:
dependencies:
flutter:
sdk: flutter
path_provider: ^2.0.2 # Add this line
import 'package:path_provider/path_provider.dart';
import 'dart:io';
Future writeFileToExternalStorage(String fileName, String content) async {
Directory? externalDir = await getExternalStorageDirectory();
if (externalDir != null) {
String filePath = '${externalDir.path}/$fileName';
File file = File(filePath);
await file.writeAsString(content);
print('File $fileName has been written to external storage');
} else {
print('Could not get external storage directory');
}
}
String fileName = 'example.txt';
String fileContent = 'This is an example file content.';
writeFileToExternalStorage(fileName, fileContent);
Once you run the code, it will create a file called “example.txt” with the content “This is an example file content.” in the device’s external storage (if available). If successful, the message “File example.txt has been written to external storage” will be printed in the console.
Make sure to request the necessary permissions in your AndroidManifest.xml and Info.plist files to read/write external storage.