MEHEDI HASAN
MEHEDI HASAN

Reputation: 149

Flutter fetch JSON from external Storage

I am trying to read a json file from external Storage (Android). But unable to do it.

I already setup the permission in manifest also checking the permission before reading. Though the file is already in the directory cannot read it.

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;
  }

Log

I/SimplePermission(17862): Checking permission : android.permission.READ_EXTERNAL_STORAGE I/flutter (17862): Directory: '/storage/emulated/0'

the permission is successful but cannot read the file

Upvotes: 1

Views: 1067

Answers (1)

Bharat Shekhawat
Bharat Shekhawat

Reputation: 83

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}/BCS/bsc.json");

Then decode this jsonFile using

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

Upvotes: 3

Related Questions