Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

dart - How do I get the Asset's file path in flutter?

Here is my pubspec.yaml:

  assets:
    - assets/mySecertImage.png

Here is how I read back the assets:

  var data = await PlatformAssetBundle().load('assets/mySecertImage.png');

Instead of reading it directly, can I get the file path instead? If it is not possible to do so, it is possible to change the data to become a File object? Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you found a solution ? (I am looking for the same as well).

Here is a workaround that I pursue (out of lack of a better idea)... :

I do:

  • create a new File-path to your Documents-directory (named app.txt in the below code-example)
  • copy the File sitting in your assets folder to this Documents-directory location
  • work with the copied file from now on (where you now have File-path and even Byte-content if needed)

Here is the Dart-code:

import 'package:path/path.dart';

Directory directory = await getApplicationDocumentsDirectory();
var dbPath = join(directory.path, "app.txt");
ByteData data = await rootBundle.load("assets/demo.txt");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);

Some people also work with the getDatabasesPath() instead of getApplicationDocumentsDirectory(). But I figured that on an iOS-Simulator this ends up being the exact same location. (not verified on Android)... So, it would say:

var dbDir = await getDatabasesPath();
var dbPath = join(dbDir, "app.txt");
ByteData data = await rootBundle.load("assets/demo.txt");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(dbPath).writeAsBytes(bytes);

For an iOS-Simulator: In both above examples, you can find your copied file under the folder:

/Users/username/Library/Developer/CoreSimulator/Devices/AE5C3275-CD65-3537-9B32-53533B97477C/data/Containers/Data/Application/7BE2B2EE-4E45-3783-B4BD-341DA83C43BD/Documents/app.txt

(of course, the UUID's being different in your case...)

And if you want to copy the file only if it does not exist already, you could write:

Directory directory = await getApplicationDocumentsDirectory();
var dbPath = join(directory.path, "app.txt");
if (FileSystemEntity.typeSync(dbPath) == FileSystemEntityType.notFound) {
  ByteData data = await rootBundle.load("assets/demo.txt");
  List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
  await File(dbPath).writeAsBytes(bytes);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...