How to store and access JSON objects in arb file in flutter?

I am implementing localization in flutter. From what I read in docs I get that all the translations should be in root/lib/l10n/ folder. I have two files in it app_en.arb and app_hi.arb. I have followed this official doc on flutter localization. As I read I got to know that arb file takes json format. With the example given in the doc, which takes key-value pair it works fine.

{
"helloWorld": "Hello World!",
"@helloWorld": {
      "description": "The conventional newborn programmer greeting"
}                                                                                             
}

But what I want is to store json object like this for translation

app_en.arb

{
"helloWorld": "Hello World!",
"@helloWorld": {
      "description": "The conventional newborn programmer greeting"
},
"content": [
  {
    "id": "one",
    "question": "What's your name?"
  },
  {
    "id": "two",
    "question": "What's your name?"
  }
]  
}

app_hi.arb

{
"helloWorld": "नमस्ते",
"content": [
    {
        "id": "एक",
        "question": "आपका नाम क्या है?"
    },
    {
        "id": "दो",
        "question": "आपका नाम क्या है?"
    }
]                                                                                             
}

But it throws an error

The value of "content" is not a string. Generating synthetic localizations package has failed.

is it possible to store json objects like this? if not, what is the alternate way?

1 answer

  • answered 2021-09-12 07:04 Niklas von Haxthausen

    .arb localization is very opinionated about its format. Therefore having an arbitrary data structure in there does not work because it relies on the Flutter analyzer to parse it and generate a 'FooLocalizations' class inside your .dart_tool/flutter_gen/ folder. If you wanna use an arbitrary JSON format - just create JSON files inside your assets folder and access them via rootbundle.load(path) and serialize the bytes into JSON format :)

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum