简体   繁体   中英

How to read a json file without assets with flutter

I'm trying to execute a json file that shows 2 routes with bat files.

To read the file I'm using a path_provider to localize the json file, so that part I have it already done. I need to know why the program can't reconize the text. I put all the information inside a list bc is the correct way to read all the information.


dynamic complete_route = '';

_functionX(String args1, String args2) async {
  var shell = Shell();
  try {
    final dir = await getApplicationDocumentsDirectory();
    String d = dir.path;
    final path = d;

    final route = await ('$path\\config.json');

    String contenido = await _leerArchivo(route);
    String local_route = complete_route;

    shell.run('$local_route $args1 $args2');
  } catch (e) {
    debug('error', true);
    debug(e, true);
  }
}

List lista = [];

_leerArchivo(String ruta) async {
  try {
    //final File f = File(ruta);

    final res = await json.decode(ruta);

    lista = res["routes"];

    complete_route = res.toString();

    return lista;
  } catch (e) {
    return e.toString();
  }
}

Add permission in menifest file

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

Put below permission in <application.... /application>

android:requestLegacyExternalStorage="true"

rootBundle is used to access the resources of the application, it cannot be used to access the files in phone storage.

Open the file with

File jsonFile = await File("${dir.path}/demofolder/demo.json");

Then decode this jsonFile using

var jsonData = json.decode(jsonFile.readAsStringSync());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM