Flutter从外部存储中获取JSON

时间:2019-06-02 07:57:52

标签: json flutter dart

我正在尝试从外部存储(Android)读取json文件。但是无法做到。

我已经在清单中设置了权限,还需要在阅读之前检查权限。尽管该文件已经在目录中,但无法读取它。

ModelTestModel modelTestModel;
List<ModelTests> listModelTests;

Future<bool> get readPermission async {
    await new Future.delayed(new Duration(seconds: 1));
    bool checkResult = await SimplePermissions.checkPermission(
        Permission.ReadExternalStorage);
    if (!checkResult) {
      var status = await SimplePermissions.requestPermission(
          Permission.ReadExternalStorage);
      if (status == PermissionStatus.authorized) {
        var res = await fetchModelTest;
        return res != null;
      }
    } else {
      var res = await fetchModelTest;
      return res != null;
    }
    return false;
  }


  Future<List<ModelTests>> get fetchModelTest async {
    var dir = await getExternalStorageDirectory();      
    print(dir);
    final data =
        await rootBundle.loadString("${dir.path}/BCS/bsc.json");
    print(data);    
    // var data = await rootBundle.loadString('assets/database/bcs-preparation.json'); this is working when when the file is inside assets 
    var jsonData = json.decode(data);
    modelTestModel = ModelTestModel.fromJson(jsonData);
    listModelTests = modelTestModel.modelTests;

    return listModelTests;
  }

日志

  

I / SimplePermission(17862):检查权限:   android.permission.READ_EXTERNAL_STORAGE I / flutter(17862):目录:   '/ storage / emulated / 0'

许可成功,但无法读取文件

1 个答案:

答案 0 :(得分:0)

rootBundle用于访问应用程序的资源,不能用于访问手机存储中的文件。

使用

打开文件
File jsonFile = await File("${dir.path}/BCS/bsc.json");

然后使用解码该jsonFile

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