khanchutai
khanchutai

Reputation: 55

How can I reach JSON value that returns from web server on a Flutter mobile application?

I can't reach my returned JSON data value. I'm using get method for reaching and server returns the JSON with 200 but when I try to reach JSON value it gives error.

My JSON:

{
    "user": [
        {
            "id": 2,
            "userName": "Mehmet",
            "email": "[email protected]",
            "sys_role": 3,
            "tckn": "00000000000",
            "fk_parkID": 81
        }
    ],
    "parks": [
        {
            "parkID": 1,
            "parkName": "Park Name",
            "latitude": 42,
            "longitude": 29,
            "fk_regionID": 2
        }, // 107 more parks like the up one.
    ]
}

I've tried this for reaching "userName" value from "user".

var selectedUserInfo;
var parksInfo;

selectUser(id) async { // This is selecting a person for doing some process on his/her account.
    var result = CallApi().getData('admin/user/${id}', _setHeaders());

    selectedUserInfo = jsonDecode(result.body)["user"][0]["userName"];
    parksInfo = jsonDecode(result.body)["parks"];
    setState(() {

    });
}

When I

print(selectedUserInfo)

it returns null.

Upvotes: 0

Views: 31

Answers (1)

F Perroch
F Perroch

Reputation: 2215

Your getData() method is probably an asynchronous method (Future).

If you don't wait for it, the result will be null, so the selectedUserInfo.

You should add the await keyword like this :

var result = await CallApi().getData('admin/user/${id}', _setHeaders());

I hope that will solve your issue

Upvotes: 1

Related Questions