Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read .txt file from assets in Flutter?

I have a .txt file in my folder assets in the Flutter project and when the app is open on a device a SQFlite database is created and should read from this file lines to insert them in the Database. I need to read each line of the .txt file and add them to a List<String> like this :

List<String> _list = await new File('$dir/assets/file.txt').readAsLines();

I have try to use rootBundle but I can't convert the result as a File and by trying to open the file directly like this :

String dir = (await getApplicationDocumentsDirectory()).path;

I always can't find the file and get an error.

var byte = await rootBundle.load('assets/bot.txt'); // Can't convert it to file
String dir = (await getApplicationDocumentsDirectory()).path;
List<String> _list = await new File('$dir/assets/file.txt').readAsLines(); // Error

error FileSystemException: Cannot open file, path = '/data/user/0/com.example.animationexp/app_flutter/assets/file.txt' (OS Error: No such file or directory, errno = 2) during open, closing...

Is there a solution for me to open and read this file ?

like image 952
zackattack Avatar asked May 17 '19 12:05

zackattack


2 Answers

It's not working because you just assumed that your assets directory is at ApplicationDocumentsDirectory, then you joined both directories and looked for the file in a path that doesn't exist.

Instead, you should save your file to disk in a known path, and then get the File from that path:

Future<List<String>> getFileLines() async {
  final data = await rootBundle.load('assets/bot.txt');
  final directory = (await getTemporaryDirectory()).path;
  final file = await writeToFile(data, '$directory/bot.txt');
  return await file.readAsLines();
}

Future<File> writeToFile(ByteData data, String path) {
  return File(path).writeAsBytes(data.buffer.asUint8List(
    data.offsetInBytes,
    data.lengthInBytes,
  ));
}

However, if your file is just a simple text file, you should try Julien Lachal's approach. Just keep in mind that rootBundle.loadString() won't work for most file formats.

like image 156
Hugo Passos Avatar answered Sep 22 '22 23:09

Hugo Passos


After having declared the file in pubspec.yml you could simply get the content using:

String fileText = await rootBundle.loadString('assets/file.txt');
print(fileText);
like image 28
Julien Lachal Avatar answered Sep 18 '22 23:09

Julien Lachal