I have ckecked all the answers about reading and writing file in Flutter. None of them answers the question of how to display a text file on the screen of the phone.
All I want to do is to have a function/method to call with the filename as input, which will display a short text file from my assets directory on a new screen on the phone that I have navigated to. The file is correctly placed in assets and mentioned in the yaml file. I have seen the suggestion to use:
Future loadAsset() async {
return await rootBundle.loadString('assets/my_text.txt');
}
but I don't know how to use it and what code to use to display a file on the screen.
I suppose that you know how to display a Text on the Screen, so I will just try to explain how I normally read files.
First you have to import:
and then, in your class, you can use this:
At the end, the content of your file is in linesAsList as a list of lines.
First this code to have a new screen and call your code:
It prints Button 1 got pressed on console and goes fine to new screen indled, which has the code:
It prints 'Indledning 2' on the screen as a test, but nothing more happens. I have your code as the following in a separate file:
On the line: List linesAsList = await myFile.readAsLinesSync(); I get a warning on await: Await only futures so I took out await. But same result if await is included.
I have tried to put fileName instead of "my file.txt" in your code, but same result.
This is my example code:
Things you must be aware of, we are creating:
Because, it's StatefulWidget and in every interaction State class rebuilds itself, so your app will execute FutureBuilder every time, which is very bad.
loadString method is async with String return type, if you are a beginner for Flutter, use FutureBuilder to handle Future returns for now. There are other ways more useful but a bit advanced.
Don't build the widget unless you are sure FutureBuilder gets the data with this conditional: