'Flutter can't find txt file

I'm trying to use the INI Package to read a file, but when I'm trying to access the file just by reading its contents I get the following error: No such file or directory.

Here is the faulty code:

class _FactsListScreenState extends State<FactsListScreen> {
  @override
  Widget build(BuildContext context) {
    File file = File("Assets/Facts/English.txt");
    Config config = Config.fromStrings(file.readAsLinesSync());
    print(config.sections());

Interesting, but when using rootBundle.loadString("Assets/Facts/English.txt") it works, but not when using File("Assets/Facts/English.txt")

I also need to mention that I'm running the app on an Android simulator, if that makes any difference.

Yes, I have included the folder in pubspec.yaml:

pubspec.yaml screenshot

Here is my file structure to show that the file is actually there:

File Structure

What's the problem with the code? Why it can't find the file?



Solution 1:[1]

You can't use File to read files from assets due to File is a reference to a file on the file system. You can't access assets files by File. Whenever you tried calling like

File file = File("Assets/Facts/English.txt");

it will try to read files from a device not from the app's assets folder.

You could use the below function to make file from assets.

Future<File> getImageFileFromAssets(String path) async {
  final byteData = await rootBundle.load('assets/$path');

   final file = File('${(await getTemporaryDirectory()).path}/$path');
    await file.writeAsBytes(byteData.buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

  return file;
}

Solution 2:[2]

You can change your pubspec file to only:

Assets/

And then call:

File file = File("Facts/English.txt");

Solution 3:[3]

Rename your Asset directory to assets (small case). because as per the flutter official document (name libraries, packages, directories, and source files using lowercase_with_underscores.fileextension)check this link for reference.

so in your case do following things:

1. Rename your Asset directory to assets 
2. Rename subdirectories to audio, facts
3. also rename file to english.txt 

use string file path like thin 'assets/facts/english.txt'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Gerry
Solution 3 Vishal Zaveri