I’m creating a console application to read a local file using the following code:
note: I need to store the result in to a List so that I can use it later on in the code. Printing was just an example of what I want to do with it later. And I cant do everything inside the file read routine. I need access to the List later.
var text = new List();
var config = new File("myfile.txt");
config.readAsLines(Encoding.ASCII).then((List<String> lines) {
text.add(lines);
});
for (var l in text) print (l);
clearly this wont work, things like this is what I really dislike about dart. So how else am I supposed to do this without using sync? sync is no good because I need to write this code all in the “main” section without calling any voids to handle the input. Also If I use sync and do a loop through a selection of files in a directory and try to add it to a list and print the output it will repeat printing the output of the first file in the directory.
so is there some kind of “trick” to make this work how I’m trying to do it? such a strait forward simple operation in any other scripting language not so strait forward in dart 🙁
Many of APIs in dart use async operations. Usually, this operations return Future. Once result of operation is available the function given at
Future.thenis called.In your exemple,
text.add(lines)is called afterfor (var l in text) print (l);and so thetextlist is still empty when you try to read its content. To make you code work, you have to put theprintinto the callback function. Something like :You can also use synchronous versions of asynchronous File functions. Particulary readAsLinesSync which is the synchronous version of readAsLines. With that version, your code can be :