I apologise in advance if this is a silly question, but I have created a file and stored it in my "assets" sub-directory, which is at the same level as my lib directory and my pubspec.yaml file. I’ve set the relative path to "assets/ExerData.json" in my code (see below).
When I run the code saved as a scratch.dart file as shown below, hitched up to a Galaxy Nexus API 29 emulator, it can only tell me "Can’t find file!"
import 'dart:io';
import 'package:flutter/services.dart';
String filePath = "assets/ExerData.json";
void main() {
performTasks();
}
void performTasks() {
if (checkFileExists(filePath)) {
readFile(filePath);
} else {
print("Can't find file");
}
}
bool checkFileExists(path) {
bool result = File(path).existsSync();
print(result.toString());
return result;
}
Future<String> readFile(path) async {
return await rootBundle.loadString(filePath);
}
I populated my pubspec.yaml file with this entry:
assets:
- assets/ExerData.json
I expected it to find my file, read it using rootbundle.loadstring(path), and print out the resulting string to the console.
As I say, all it did was print "Can’t find file".
I’d very much appreciate you help on this one!
Thanks in advance!
3
Answers
As it turns out, the program logic had not completed initializing the necessary binding.
I called the method
WidgetsFlutterBinding.ensureInitialized()
in the first line of the main class and everything started working as I expected.Thanks to everyone who looked at my question!
Here's a similar question involving binding with XML files: How to read XML files in flutter?
The
rootBundle
contains the resources that were packaged with the app when it was built. All files specified underassets:
in yourpubspec
are packaged with the app. You can check if file exists by wrappingrootBundle.loadString()
insidetry{} catch(){}
block.or
File is a dart class. It needs absolute or relative path of the file being read.
You can use
File
withpath_provider
to get the absolute path from the current File System.For example on Android:
prints
Use:
Reference: How to load JSON assets into a Flutter App?