Use Flutter 'file', what is the correct path to read txt file in the lib directory?
Create an assets folder in your project's root folder. In Android Studio you can right click the Project outline and go to New > Directory
.
So now you should have
root folder
--android
--ios
--lib
--assets
--build
Add your text file to the new folder
You can just copy your text file into the assets directory. The relative path of words.txt
, for example, would be assets/words.txt
.
Open the pubspec.yaml file that is in the root of your project. Update it as
flutter:
assets:
- assets/words.txt
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
Future<String> loadAsset() async {
var s = await rootBundle.loadString('assets/my_text.txt');
print(s);//for debug
return s;
}
Zephan
Updated on December 10, 2022Comments
-
Zephan 27 minutes
I am using the flutter 'file', trying to read a
txt
file in lib directory, but I do not know how should I write in code to read the file. I also do not know if I have placed thetxt
file at a right place, which means I do not know if I can read the file in the lib directory.I have put a
txt
filewords.txt
in the lib directory, where other dart files are put.Below is my code which tries to read the 'word.txt' file:
Future<String> readFile() async { var text; try { final directory = await getApplicationDocumentsDirectory(); print(directory.path); final file = File('${directory.path}/lib/words.txt'); text = await file.readAsString(); return text; } catch (e) { print(e.message); } }
P.S. I have imported the 'dart:io' and 'path_provider.dart'.
When I run the program, I can see the directory.path is printed in the console, however the e.message 'Cannot open file' is printed in the console.
I think that the error is came from 'File('${directory.path}/lib/words.txt')', so i would like to know how should i write code to read the txt file in lib directory.
Thanks.