-1

I have json array like this

{
    "result": [
        {
            "nik": "1234",
            "name": "test"
        }
    ],
    "status_code": 200
}

How I can get all data from that json array/object?

and this my flutter code

final jsonData = json.decode(response.body);
    Sample sample = Sample.fromJson(jsonData);
    setState(() {
      print(sample.result);
    });

class Sample {
  String result;
  int code;
  Sample({required this.result, required this.code});
  @override
  factory Sample.fromJson(Map<String, dynamic> json) {
    return Sample(
        result: json["result"],
        code: json["code"]
    );
  }
}

but I got this error

Error: Expected a value of type 'String', but got one of type 'List<dynamic>'
at Object.throw_ [as throw] (http://localhost:53292/dart_sdk.js:5041:11)
Eggy
  • 522
  • 5
  • 29
  • If you get data from API refer my answer [here](https://stackoverflow.com/a/68709502/13997210) or [here](https://stackoverflow.com/a/68533647/13997210) or [here](https://stackoverflow.com/a/68594656/13997210) hope it's helpful to you – Ravindra S. Patil Sep 13 '21 at 03:52

2 Answers2

0

You could get past writing that error prone boilerplate using a package like json_serializable or by easily generate dart models just from a json using quicktype

croxx5f
  • 5,163
  • 2
  • 15
  • 36
0

result is an array, so you need List to save the data. Just create a model named User.

class User {
  String nik;
  String name;
  Sample({required this.nik, required this.name});
  @override
  factory User.fromJson(Map<String, dynamic> json) {
    return User(
        nik: json["nik"],
        name: json["name"]
    );
  }
}

Create a field List<User> in Sample class. Then use fromJson from User class to parse the result json. Or use json_serializable package

Ananda Pramono
  • 899
  • 1
  • 6
  • 18