Read a section/part of a long .txt asset file in dart - Flutter

Viewed 137

I have a .txt file in assets folder that I can read, but now I want to read a section of the file maybe from point A to point B. My current code to read the whole file's contents is shown below

  Future<void> readText() async {
    final String response =
        await rootBundle.loadString('assets/longtextfile.txt');
    setState(() {
      dataFromFile = response;
    });
  }

then I display like this...

             child: Center(
                child: Text(
                  dataFromFile,
                  style: TextStyle(color: Colors.white, fontSize: 20.0),
                ),
              ),

how do I read the files contents line by line from point A to point B of the long txt file?

longtextfile.txt looks like

1. song 1
 some text
 some text
 some text

2. song 2
 some text
 some text
 some text

3. song 3
 some text 
 some text 
 some text

so I want to read for example song 2 only, how do I do that?

1 Answers

You can split the string into lines by using split from the LineSplitter class:

final lines = LineSplitter.split(dataFromFile);

Then you can do anything you like with the lines. You can take only a few of them, have seperate widgets for them that have seperate style, whatever you want.


Since you posted your data now. You can for example get the song that is number 2 by looking at the lines using the skipWhile and takeWhile methods:

final song2 = lines.skipWhile(line => !line.startWith('2'))
                   .takeWhile(line => !line.startWith('3'));

for(final line in song2) {
    print(line);
}
Related