Reputation: 95
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:
Here is my file structure to show that the file is actually there:
What's the problem with the code? Why it can't find the file?
Upvotes: 1
Views: 1704
Reputation: 911
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;
}
Upvotes: 3
Reputation: 1557
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'
Upvotes: 0
Reputation: 1479
You can change your pubspec file to only:
Assets/
And then call:
File file = File("Facts/English.txt");
Upvotes: 0