Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a "TXT" file in Dart

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

like image 606
Roby Avatar asked Sep 16 '18 00:09

Roby


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();
like image 88
Richard Heap Avatar answered Oct 09 '22 11:10

Richard Heap


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

like image 44
Chris Reynolds Avatar answered Oct 09 '22 09:10

Chris Reynolds