FileSystemException: Cannot open file, path = 'assets/busStops.txt' (OS Error: No such file or directory, errno = 2)

Viewed 4191

I can't seem to load my txt file stored in assets. Whenever I try to access it, I get the following error:

FileSystemException: Cannot open file, path = 'assets/busStops.txt' (OS Error: No such file or directory, errno = 2)

I've added the file to my pubspec file too:

  assets:
    - assets/BusSD.png
    - assets/SubtractBD.png
    - assets/VectorDD.png
    - assets/busRoutes.txt
    - assets/busStops.txt

This is my code for accessing the file


class FileUtilsBusStopInfo {
  static Future<String> get getFilePath async {
    final directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }

  static Future<File> get getFile async {
    //final path = await getFilePath;

    return File('assets/busStops.txt');
  }

  static Future<File> saveToFile(String data) async {
    final file = await getFile;
    return file.writeAsString(data);
  }

  static Future<String> readFromFile() async {
    try {
      final file = await getFile;
      String fileContents = await file.readAsString();

      print(fileContents);
      return fileContents;
    } catch (e) {
      print(e);
      print('returning blank');
      return "";
    }
  }
}

The images load fine though. What can I do to resolve this issue? Thank you in advance!

1 Answers

Try to load a file by:

import 'package:flutter/services.dart' show rootBundle;

// Method
final data = rootBundle.load('assets/busStops.txt');
// ...

Assets in Flutter are loading by its services, not from a device's filesystem.

Related