Reputation: 79
I am receiving a dynamic response from my API, but I do not know how to retrieve it like inside data the fields are changing:
{
"status": "ERROR",
"data": {
"email-common": "This email already exists."
}
}
Another time it might look like this:
{
"status": "ERROR",
"data": {
"password": "passwords do not match"
}
}
I know the code in Java but in flutter I don't know how to do it. Idea can be get from this Java code
JSONObject data = result.getJSONObject("data");
Iterator<String> keys = data.keys();
while (keys.hasNext()) {
String key = keys.next();
Log.d("myTag", data.get(key).toString());
}
If I do it for password then it's throwing errors, for the other one my question is whatever values there is I can retrieve it (dynamic retrieval)
Future<Map> getJson() async {
String apiUrl = 'http://3.127.255.230/rest_ci/api/customers';
Map<String,String> headers = {'Content-Type':'application/json','Authorization':'mykeyyyy'};
final msg = jsonEncode({
"username":"tesstestt123",
"email":"[email protected]",
"password":"testtest",
"confirm_password":"testtest",
});
http.Response response = await http
.post(apiUrl,
headers: headers,
body: msg, );
return json.decode(response.body); // returns a List type
}
void khan() async {
getJson();
String _body = "";
Map _data = await getJson();
_body = (_data['status']);
print(_data);
if (_body == 'ERROR') {
setState(() {
_isLoading = false;
});
print("$_data");
showDialog(
context: context,
builder: (c) {
return AlertDialog(
title: Text("oops"),
content: Text(_data['data']['password']),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text("Close"),
)
],
);
});
}
Upvotes: 1
Views: 8125
Reputation: 1514
Basically: you can use a function to fetch data and use it in future builder.
Fetching data:
Future<dynamic> getData() async{
http.Response response = await http.get("url");
return jsonDecode(response.body);
}
Using in Future Builder:
FutureBuilder<dynamic>(
future: getData(),
builder: (context, snapshot) {
if (snapshot.hasError) {
return Text(
'There was an error..',
);
}
else if (snapshot.hasData) {
return Text(snapshot.data['id'])
}})
Or you can use it as var and write directly
jsonDecode(response.body)['results']
Upvotes: 0
Reputation: 5987
Dart has built-in support to decode a JSON string. Like this:
Map<String, dynamic> jsonMap = json.decode(yourJSONString);
You can access any values inside this map like you would do in Java
print(jsonMap["status"]);
print(jsonMap["data"]["password"]);
If you just always want to access the values inside "data" without knowing they keys you could iterate them:
Map<String, dynamic> dataMap = jsonMap["data"];
dataMap.keys.forEach((k) {
print(k);
print(dataMap[k]);
});
Upvotes: 1