jsonflutterdartfutureformatexception

Flutter throwing FormatExceptio when trying to read a JSON file


I have the following function:

  void readJSON(String path) async {
    
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path + '/' + path;
    print('Trying to read json file from ' + appDocPath);
    
    final Future<String> response = File(appDocPath).readAsString();
    final data = await json.decode(response.toString());
    final coordinates = await (data['elements'] as List).cast<double>();
    
    for(int i = 0; i <= coordinates.length; ++i){
      print(i);
    }
  }

As you can see, I am iterating through every JSON line to print it and see what it contains.

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected character (at character 1)
[        ] E/flutter ( 8316): Instance of 'Future<String>'

Where exactly am I going wrong?

Output:

[  +81 ms] E/flutter (10493): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected end of input (at character 1)
[        ] E/flutter (10493): 
[        ] E/flutter (10493): ^
[        ] E/flutter (10493): 
[        ] E/flutter (10493): #0      _ChunkedJsonParser.fail (dart:convert-patch/convert_patch.dart:1383:5)
[        ] E/flutter (10493): #1      _ChunkedJsonParser.close (dart:convert-patch/convert_patch.dart:501:7)
[        ] E/flutter (10493): #2      _parseJson (dart:convert-patch/convert_patch.dart:36:10)
[        ] E/flutter (10493): #3      JsonDecoder.convert (dart:convert/json.dart:612:36)
[        ] E/flutter (10493): #4      JsonCodec.decode (dart:convert/json.dart:216:41)
[        ] E/flutter (10493): #5      file.readJSON (package:camera_example/file.dart:50:29)
[        ] E/flutter (10493): <asynchronous suspension>
[        ] E/flutter (10493): 
[   +5 ms] E/flutter (10493): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: type 'String' is not a subtype of type 'int' of 'index'
[        ] E/flutter (10493): #0      file.readJSON (package:camera_example/file.dart:52:36)
[        ] E/flutter (10493): <asynchronous suspension>
[        ] E/flutter (10493): 

Solution

  • string response = await File(appDocPath).readAsString();
    

    You missed await for a future