How can I overwrite an assets image in Flutter having a source image?

好久不见. 提交于 2021-02-11 00:27:18

问题


I'm fairly new to Dart and Flutter, and I'm having trouble to overwrite an existing assets image from a source image.

My attempt:

try {
 File localFile = File('assets/images/myImage.png');
 localFile.writeAsBytesSync(originFile.readAsBytesSync());
catch (e) {
 log(e.toString());
}

I get:

[log] FileSystemException: Cannot open file, path = 'assets/images/myImage.png' (OS Error: No such file or directory, errno = 2)

I did define the assets folder in pubspec.yaml:

 assets:
    - assets/images/

Ok, so I've read somewhere that the asset file can be accessed like this:

import 'package:flutter/services.dart' show rootBundle;
final byteData = await rootBundle.load('assets/images/myImage.png');

But I don't know how to convert byteData to a File object that represents the actual file.

I think I'm missing something very basic here. Or maybe is there is a proper way to do this that has nothing to do with this approach?

Please help.

Thanks in advance!


回答1:


If you want to write a file on a user device you should look here: https://flutter.dev/docs/cookbook/persistence/reading-writing-files

Shared preferences are a space in a phone where you app can write, so it's exactly what you want!

Assets are part of you app and are not meant to be modified within the app.

During a build, Flutter places assets into a special archive called the asset bundle that apps read from at runtime. According to the flutter website

Hope this helps!



来源:https://stackoverflow.com/questions/62497533/how-can-i-overwrite-an-assets-image-in-flutter-having-a-source-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!