jsonflutterdartformatexception

Flutter throws FormatException error when JSON string is inputted correctly


Flutter is giving me this error:

[ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FormatException: Unexpected end of input (at character 88586)
[        ] E/flutter ( 5286): ...820457458, -0.09168463200330734, 0.9341723918914795, 0.9910492897033691]}",

This is how I am inflating the list (that is later written to a JSON file):

for(var i = 0 ; i <=32; ++i) {
            String entry = '{contents: ['
                '${contentList.content[i].x.toString()}, '
                '${contentList.content[i].y.toString()}, '
                '${contentList.content[i].z.toString()}, '
                '${contentList.content[i].visibility.toString()}, '
                '${contentList.content[i].presence.toString()}]}';
            content_collector.add(entry);
          }

content_collector is then passed to this function to write to a JSON file:

  Future<File> saveToJSONFile(List<String> contents_list, String filename) async {
    String encodedContents = jsonEncode(contents_list);
    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path + '/' + filename;

    return await File(appDocPath).writeAsString(encodedContents);
  }

and I have this function to read the generated JSON file:

void readJSON(String path) async {

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path + '/' + path;

    String response = await File(appDocPath).readAsString();
    final data = await json.decode(response.toString());

  }

So really, it is the readJSON function that throws this error.


Solution

  • This part is not valid JSON

    {contents: [
    

    it should be

    {"contents": [
    

    Most likely the other parts needs to be surrounded with " as well