How to go on about receiving JSON array in flutter and parsing it?

Easily

      String arrayText = '[{"name": "dart1","quantity": 12 },{"name": "flutter2","quantity": 25 }]';

      var tagsJson = jsonDecode(arrayText);
      List<dynamic> tags = tagsJson != null ? List.from(tagsJson) : null;

      print(">> " + tags[0]["name"]);
      print(">> " + tags[1]["name"]);
      print(">> " + tags[0]["quantity"].toString());
      print(">> " + tags[1]["quantity"].toString());

output

2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> dart1
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> flutter2
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> 12
2021-04-28 18:55:28.921 22085-22225/com.example.flutter_applicationdemo08 I/flutter: >> 25

You can do the following:

String receivedJson = "... Your JSON string ....";
List<dynamic> list = json.decode(receivedJson);
Fact fact = Fact.fromJson(list[0]);

In any case, you must consider the following in your json string and the Fact class that you have crafted:

  • In the json string the id and fact_id are Strings and you treat them as int. Either you change the json or the Fact class
  • Some strings inside the json string produce errors as the have additional quotation marks and this confuses the decoder.

A json string the works is the following:

String receivedJson = """
[
    {
        "id": 407,
        "fact": "Monsanto once tried to genetically engineer blue cotton, to produce denim without the use of dyes, reducing the pollution involved in the dyeing process.   ",
        "reference": null,
        "image": "http:\/\/quickfacts.me\/wp-content\/uploads\/2015\/06\/fact492.png",
        "fact_id": 1
    }
]
    """;

Tags:

Json

Dart

Flutter