Home > Mobile >  Can't read files in Flutter on all platforms, the file can be seen on linux desktop but web(chr
Can't read files in Flutter on all platforms, the file can be seen on linux desktop but web(chr

Time:11-05

import 'dart:io';
import 'package:path/path.dart';

Future<Map?> readFile(lang) async {
  var pathToFile = join(dirname(Platform.script.toFilePath()), 'text', '$lang.toml');
  var document = File(pathToFile);
  return document;
}

So I have a text directory in my flutter root directory which contains some TOML files, I have no trouble accessing these files on linux but as soon as I run this on android I get a (OS Error: No such file or directory, errno = 2), and same on web but without the error message, it just returns null, I have also tried this as well:

var document = File('text/$lang.toml');

once again, same result. I have seen people use the path_provider package for this but it didn't work anyway, and I would also like to have web compatibility. Anyone know how to solve this? TY

CodePudding user response:

When using shipped assets, you shouldn't use the host's file system. Instead use the rootBundle from flutter/services.

import 'package:flutter/services.dart';

...

Future<String> readFile(String lang) {
  return rootBundle.loadString('text/$lang.toml');
}

Assuming the file is in a text/ directory at the root of your project and it is defined in the pubspec.yaml:

flutter:
  assets:
    - text/

The fact that it worked on Linux is kind of a coincidence, since you're running and developing on the same machine. This solution should work independent of which platform you're targeting.

  • Related