Ahmad
Ahmad

Reputation: 95

conver json map to list in flutter

I am new to coding and I have a Json file, locally stored. I have accessed the file but when I store the Json data in a list, it throws a binding error. Any help is highly appreciated.

Future<void> readJson() async {
    final response = await rootBundle.loadString('assets/json/units.json');
    final data = await json.decode(response);

    setState(() {
      List jsonList = data["length"];
      print(jsonList);
    });
  }

here this is how the json data look like.

{
    "length" : [

        {

            "name": "Meter",

            "conversion": 1.0,

            "base_unit": true

        },

        {

            "name": "Millimeter",

            "conversion": 1000.0

        },

        {

            "name": "Centimeter",

            "conversion": 100.0

        }
]
}

I have tried many things but nothing has worked so far.

Upvotes: 2

Views: 61

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17880

You need to cast your data to List, like this:

List jsonList = data["length"] as List;

Upvotes: 2

Mohsen Mohamed
Mohsen Mohamed

Reputation: 11

You need to determine what is the data type of the list for example if you want your list to be list of double to be able to hold distances you can try this code

jsonList = (data["length"] as List).map((e)=>e["conversion"]).toList();

Upvotes: 0

Related Questions