skip to Main Content

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


  1. Chosen as BEST ANSWER

    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?


  2. The rootBundle contains the resources that were packaged with the app when it was built. All files specified under assets: in your pubspec are packaged with the app. You can check if file exists by wrapping rootBundle.loadString() inside try{} catch(){} block.

      Future<bool> fileExists(String path) async {
        try {
          await rootBundle.loadString(path);
        } catch (_) {
          return false;
        }
        return true;
      }
    

    or

      Future<String?> loadFile(String path) async {
        try {
          return await rootBundle.loadString(path);
        } catch (_) {
          // File not found Exception
          return null;
        }
      }
    

    File is a dart class. It needs absolute or relative path of the file being read.
    You can use File with path_provider to get the absolute path from the current File System.

    For example on Android:

     Future<void> getPath() async {
        Directory appDocDir = await getApplicationDocumentsDirectory();
        String appDocPath = appDocDir.path;
        print('PATH IS : $appDocPath');
      }
    

    prints

    '/data/user/0/com.soliev.file_demo/app_flutter'

    Login or Signup to reply.
  3. Use:

    String data = await DefaultAssetBundle.of(context).loadString("assets/ExerData.json");
    final jsonResult = jsonDecode(data); 
    

    Reference: How to load JSON assets into a Flutter App?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search