Loading txt file as an asset for a dart package

Viewed 433

In flutter it's easy to load a .txt asset at runtime by specifying it or its folder in the pubspec.yaml file and then loading it with rootBundle. However, i'm working on a pure dart package, and I'm struggling to work out how to get the package to load a .txt file relative to it's own directory structure.

When I use the package in a separate dart command line application i'm working on, the relative path that I specified in one of the package source code files causes an error to be thrown that the txt file doesn't exist. I understand why this error is being thrown, because the relative path is interpreted as being from the command line application's root directory instead of the package's root directory, but i'm unsure of how to solve this without specifying the absolute path for the .txt file. I'd rather not specify the absolute path as it makes the package less portable.

Is there anything similar to flutter's asset loading for a pure dart package?

1 Answers

I think you need the resolveSymbolicLinks or resolveSymbolicLinksSync methods to decode the relative path and then use the resolved path to read the txt file:

import 'dart:io';

void main() async {
  String file = '../lib/main.dart';
  var path = Uri.parse('.').resolveUri(Uri.file(file)).toFilePath();
  print(path);
  if (path == '') path = '.';
  var resolved = await File(path).resolveSymbolicLinks();
  print(resolved);

  File(resolved).readAsString().then((String contents) {
    print(contents);
  });
}

Related