Flutter write file to external storage

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:

  1. Add path_provider package dependency to your pubspec.yaml file:
  2. 
    dependencies:
      flutter:
        sdk: flutter
        
      path_provider: ^2.0.2 # Add this line
        
  3. Import the necessary packages in your Dart file:
  4. 
    import 'package:path_provider/path_provider.dart';
    import 'dart:io';
        
  5. Create a function to write the file:
  6. 
    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');
      }
    }
        
  7. Call the function to write the file:
  8. 
    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.

Leave a comment