Can't copy image to assets folder on real device flutter

Viewed 88

When I select an image from gallery on iPhone, i want to copy it into the assets/images folder and display it afterwards. On Simulator everything works fine. But on real device I get the following error:

Runner[44762:20816132] [VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: FileSystemException: Cannot copy file to '../../assets/images/image_picker_39C262A3-37A8-4167-8A9A-809C05C6DA67-44762-000025ACD7154E4A.jpg', path = '/private/var/mobile/Containers/Data/Application/4691143F-EC0F-470D-B7EC-88A9BCF021F8/tmp/image_picker_39C262A3-37A8-4167-8A9A-809C05C6DA67-44762-000025ACD7154E4A.jpg' (OS Error: No such file or directory, errno = 2)
#0      _File.copy.<anonymous closure> (dart:io/file_impl.dart:328:9)
#1      _rootRunUnary (dart:async/zone.dart:1434:47)
#2      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
<asynchronous suspension>
#3      _ProductInputPageState.getFromGallery (package:outfitcreator/pages/product_input_page.dart:451:9)
<asynchronous suspension>

I put the folder into the pubspec.yaml.

flutter:
  assets:
    - assets/images/

Do you have any suggestion how to encounter this?

Thank you very much!

1 Answers

You cannot copy files to your asset folder in runtime. After you pick the image you can save it to the temp dorectory or any other device folders like this

final Directory docDir = await getApplicationDocumentsDirectory();
final String localPath = docDir.path;
File file = File('$localPath/${path.split('/').last}');
final imageBytes = await rootBundle.load(path);
final buffer = imageBytes.buffer;
await file.writeAsBytes(
    buffer.asUint8List(imageBytes.offsetInBytes, imageBytes.lengthInBytes));
Related