2

My flutter app has the following assets.

assets:
 - "images/01.png"
 - "images/02.png"
 - "images/03.png"
 ...

I'd like to copy these image files to the local path I can get by the following.

 Directory docDir = await getApplicattionDocumentsDirectory();
 String localPath = docDir.path;
hrsma2i
  • 4,045
  • 6
  • 15
  • 24

4 Answers4

7

Create a file in your application directory and copy your asset image byte by byte to that file. That's it! You copied your file.

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));
Can Karabag
  • 1,695
  • 15
  • 31
0

getApplicationDocumentsDirectory you need path_provider package. Suppose you want to copy an m4a file to your application document directory

pubspec.yaml

 assets:
    - assets/audio/no_sound_3n.m4a

Your code

import 'package:path_provider/path_provider.dart';

final Directory docDir = await getApplicationDocumentsDirectory();
final String localPath = docDir.path;
File file = File(localPath);
final asset = await rootBundle.load("assets/audio/no_sound_3n.m4a");
final buffer = asset.buffer;
await file.writeAsBytes(
    buffer.asUint8List(asset.offsetInBytes, asset.lengthInBytes));

You asset folder

enter image description here

-1

I too couldn't find a way yet. A way to mitigate this is following the assets guide, by specifying

flutter:
  assets:
    - assets/ 

And load arbitrary files via rootBundle

import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

Future<String> loadAsset() async {
  return await rootBundle.loadString('assets/index.html');
}

or in your case using AssetImage

Widget build(BuildContext context) {
  // ...
  return DecoratedBox(
    decoration: BoxDecoration(
      image: DecorationImage(
        image: AssetImage('graphics/background.png'),
        // ...
      ),
  // ...
    ),
  );
  // ...
}
eljefedelrodeodeljefe
  • 6,304
  • 7
  • 29
  • 61
-1

This thread is pretty old, but in case anyone is still looking for an answer, this is how I did it :)

  rootBundle.load('assets/test.jpg').then((content) {
    File newFile = File('${dir.path}/img.jpg');
    newFile.writeAsBytesSync(content.buffer.asUint8List());
    visionImage = FirebaseVisionImage.fromFile(newFile);
    _runAnalysis();
  });
Lennart Schoch
  • 157
  • 2
  • 3
  • 21