Home > Blockchain >  Flutter JSON SyntaxError only on Production, not in Debug mode
Flutter JSON SyntaxError only on Production, not in Debug mode

Time:05-17

In my flutter app I want to parse a JSON-file saved in the assets-directory. When I run it locally in debug mode, I can parse the file without any problems, but when it runs in production (hosted by Firebase) I get this SyntaxError:

Uncaught FormatException: SyntaxError: Unexpected token < in JSON at position 0

Here is how I read the file in the code:

Future<String> _getEmoji() async {
  String emoji;
  if (_emojiList.isEmpty) {
    final String response = await rootBundle.loadString('data-ordered-emoji.json');
    final data = json.decode(response);
    emoji = data[Random().nextInt(data.length)];
    _emojiList = data;
  } else {
    emoji = _emojiList[Random().nextInt(_emojiList.length)];
  }
  return emoji;
}

The JSON I'm using is exactly this file: https://unpkg.com/[email protected]/data-ordered-emoji.json

According to IntelliJ it's encoded in UTF-8.

What am I missing here?

EDIT: After adding a print-command in the method above to figure out how the JSON looks like I saw that it's not the JSON-file I saved in assets-directory. It's the index.html file of the build. How is that possible?

CodePudding user response:

Sorry I cannot comment, so I post this answer.

It is possible that the json is packed inside '<' and '>' so json decoder cannot decode it.

I suggest you first print the response and check for this unexpected character. In case there is this strange character just remove the first and last character.

String loginToken="<Hello>";
System.out.println(loginToken.substring(1, loginToken.length()-1))

Output: Hello

Further examples: How to use substring dart

CodePudding user response:

Solved it. The problem was that the assets directory was not included in the build. Therefore I had to add this to the pubspec.yaml file:

flutter:
  assets:
      - assets/

Than the assets directory is included in build/web/assets and the JSON is available on production. Strange that the index.html was taken instead though.

  • Related