Read a "TXT" file in Dart

Viewed 3838

i was trying to read a .txt file (from assets) in items of a list, so i was doing this:

list.add(await rootBundle.loadString('assets/jolo.txt'));

It takes the whole document and put it in 'data', but at showing the list is empty.

So i tried something else:

new File('assets/jolo.txt')
  .openRead()
  .transform(utf8.decoder)
  .transform(new LineSplitter())
  .forEach((l) => list.add(Item(name: l)));

but that throws me an error: FileSystemException: Cannot open file, path = 'assets/jolo.txt' (OS Error: No such file or directory, errno = 2)

What can i do? I'm using plain text for putting every line into an item for show the whole list

2 Answers

To load an asset you must use the bundle. loadString takes care of reading the asset and dealing with the encoding so you get a String. Use LineSplitter.convert on the string:

String jolo = await rootBundle.loadString('assets/jolo.txt');
List<Item> list =
    LineSplitter().convert(jolo).map((s) => Item(name: s)).toList();

You may not be running in the directory that you think. Try looking at Directory.current() to see where you are running.

Related