Write file in flash drive (android only)

424 Views Asked by At

Is it possible to save files to a flash drive using flutter?

I'm using a pendrive with a USB c port like this: https://www.bestbuy.com/site/sandisk-ultra-dual-drive-go-1tb-usb-type-a-usb-type-c-flash-drive-black/6560692.p?skuId=6560692

I found this issue: https://github.com/flutter/flutter/issues/40504

I've tried several things, path_provider doesn't return directories correctly with getExternalStorageDirectories()

I have already added the permissions to the manifest and requested it with permission_handler

<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="28" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>

I also tried with file_picker await FilePicker.platform.getDirectoryPath();

But when selecting a folder on the flash drive the path it returns is just: /

I also tried using usb_serial:

final bytes = <int>[];

await yt.videos.streamsClient.get(audioStream).listen((chunk) {
  bytesReceived += chunk.length;
  bytes.addAll(chunk);

}, onDone: () async{
  MyLog.log('Done onDone');

}, onError: (error) async{
  MyLog.log('Done error: $error');

}).asFuture();

final devices = await UsbSerial.listDevices();
final port = await devices.first.create();
final openResult = await port?.open();

if ( !(openResult ?? false)) {
  MyLog.log("Failed to open");
  return;

}

port?.inputStream?.listen((Uint8List event) {
  MyLog.log('Event close');
  port.close();
});

await port?.write(Uint8List.fromList(bytes));

But it did not work

1

There are 1 best solutions below

0
TitoSenpai On

Try using Flutter’s platform channels to communicate with native Android code (Java or Kotlin) that handles the file operations on the USB drive.

flutter:

import 'package:flutter/services.dart';

class UsbStorage {
  static const platform = const MethodChannel('com.example.app/usb');
   ~~~code
}

kotlin:

class MainActivity: FlutterActivity() {
  private val CHANNEL = "com.example.app/usb"

  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
~~~code
}