how to get value from list in dart/flutter? - android

I'm trying to get some currency data from a foreign exchange API. After getting data from the website,
I'm having a problem in extracting the desired value of currency pair from the list which I'm receiving after the HTTP request as data. Here's what I am doing:
Future<void> getInfo() async {
try {
print((url)); //url = EUR/USD, this value is comeing from a dropdown
URL =
"https://fcsapi.com/api-v2/forex/latest?symbol=$url&access_key=t58zo1uMFJZlNJxSrSmZv2qIUlSkCk9RAfCLkwnMwt1q1FFS";
print((URL));
Response response =
await http.get(Uri.encodeFull(URL),
headers: {"Accept": "application/json"});
data = jsonDecode(response.body);
print(data);
List info = data['response'];
print(info);
double price = ......; // I don't know what to write here I have tried everything.
print(price);
here I want to get the value of the price from the list "info" but idont know what to write in 'double price'
} catch (e) {
print('error is : $e');
}
}
this is the result on consol
I/flutter ( 4286): EUR/USD
I/flutter ( 4286): https://fcsapi.com/api-v2/forex/latest?
symbol=EUR/USD&access_key=t58zo1uMFJZlNJxSrSmZv2qIUlSkCk9RAfCLkwnMwt1q1FFS
I/flutter ( 4286): {status: true, code: 200, msg: Successfully,
response: [{
id: 1,
price: 1.1788,
change: +0.0072,
chg_per: +0.61%,
last_changed: 2020-10-05 14:47:57,
symbol: EUR/USD}],
info: {server_time: 2020-10-05 14:49:12 UTC,
credit_count: 1, _t: 2020-10-05 14:49:12 UTC}}
// this is printing due to print (data); statemet
I/flutter ( 4286): [{
id: 1,
price: 1.1788, // i want to print this value
change: +0.0072,
chg_per: +0.61%,
last_changed: 2020-10-05 14:47:57,
symbol: EUR/USD}]
// this is printing due to print (info); statemet, which is printing the responce of json
what i want :
i want to print the value of price in console after printing the responce e.g.
I/flutter ( 4286): 1.1788

this will work
double price = info[0]['price']

since the response is a list / array, you can use index to get items from the list.
var item = info[0]; // get first item from the list.
double price = item["price"];
print(price);

Related

type '_Map<String, dynamic>' is not a subtype of type 'Iterable<dynamic>

final response = await http.post(Uri.parse(AppUrl.getBooking),
headers: headers,
body: data);
var map = jsonDecode(response.body);
for(var r in map){
log(r['name'].toString());
}
first time value come but when i again come to this page its show error
Unhandled Exception: type '_Map<String, dynamic>' is not a subtype of type 'Iterable'
please help me to solve this.
i want to show table_calender event via api using provider.

Retrofit Kotlin and getting an Array?

Anyone here can give me a small hand with Retrofit? I am trying to get an Array from PHP.
This is my Response in Kotlin:
class QuestionnairesResponse (val status: Boolean, val message:String, val questionnaires: List<Questionnaire>)
Questionnaire class:
data class Questionnaire(
val id: Int,
val title: String,
val questions: List<Question>
)
Question class:
data class Question (
val id: Int,
val text: String
)
My JSON array output:
{
"questionnaires":[
{
"id":"1",
"title":"Are you hungry?",
"questions":{
"id":"1",
"text":"How is your passion? "
}
},
{
"id":"2",
"title":"How are you feeling?",
"questions":{
"id":"1",
"text":"How is your passion? "
}
},
{
"id":"5",
"title":"Is testing working?",
"questions":{
"id":"4",
"text":"How is the testing?"
}
}
],
"status":true,
"message":"Succefully got questionnaires!!!"
}
However, it seems it doesn't get the 'questions' part and it results in a failure. The strange thing is that If I change it to 'question' instead of 'questions' it doesn't result in a failure, and it gets the questionnaire details as ID and title, but stil; the question array is empty.
What is going wrong here? I can't seem to find the problem.
UPDATE: My backend needs to be fixed as questions need to be an array.
I just can't seem to wrap my head around on how to fix this issue when getting the data from MySQL....
My PHP code:
$sql = "SELECT questionnaires.id QuestionnaireId, questionnaires.title QuestionnaireTitle, questions.id QuestionId, questions.text Question
FROM questionnaires INNER JOIN questionnaireshasquestions qa ON qa.idQuestionnaire = questionnaires.id
INNER JOIN questions ON questions.id = qa.idQuestion";
$conn=$dbh->prepare($sql);
$conn->execute();
$result = $conn->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
while ($row = $conn->fetchAll()) {
$endResult['questionnaires']= $row;
}
//echo json_encode($endResult);
$idd = null;
$test = [];
foreach ($endResult['questionnaires'] as $questionnaire) {
if ($idd != $questionnaire[0]) {
$idd = $questionnaire[0];
$test['questionnaires'][] = [
'id' => $questionnaire[0],
'title' => $questionnaire[1],
'questions' => [
'id' => $questionnaire[2],
'text' => $questionnaire[3]
]
];
}
}
One questionnaire can have multiple questions.

Can't put a json on a Map on Flutter

I'm trying to get the data from a json and save into a map to use the data on my app, but i cant make it work.
Here´s the json example:
[
{
"Codigo_Produto": 2025,
"Qtde": 4,
"Descricao": "SERVIÇO DE ALINHAR EIXOS",
"Codigo": 3862,
"CodOS": 3862,
"Numero_da_OS": "3862"
},
{
"Codigo_Produto": 2423,
"Qtde": 4,
"Descricao": "SERVIÇO DE CAMBAGEM TRAÇÃO/TRUCK",
"Codigo": 3862,
"CodOS": 3862,
"Numero_da_OS": "3862"
}
]
Here is how i try to access the data:
Map<dynamic, dynamic> map =
jsonDecode(response.data);
print(map);
And i get this error:
E/flutter (15734): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
I have also tried making in different ways but everytime i get this error.
What is wrong with my code? Is it because the response is coming insite a array? What is the best way to receive and make this data usable for my app?
The full code on the button that calls the api is here:
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.2:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
print(response.statusCode);
print(response.data);
Navigator.pop(context, true);
},
Your response.data returns list. Check first line of your json, it has list brackets like this [.
You should retrieve your data this way:
final listOfObjects = <String,dynamic>[];
for(var obj in response.data)
{
listOfObjects.add(jsonDecode(obj));
}
return listOfObjects;
You need to change return type of your Future also, to list of your objects.
Using the json.decode you can extract the data directly to map
String responseBody = await rootBundle.loadString("assets/data.json");
var maplist = await json.decode(responseBody).cast<Map<String, dynamic>>();

"The getter 'body' isn't defined for the type 'Response<dynamic>". on Flutter

i'm having a problem to put a response json on a List.
When i try to transform the body data (where the data comes) i get the error:
The getter 'body' isn't defined for the type 'Response<dynamic>'.
Try importing the library that defines 'body', correcting the name to the name of an existing getter, or defining a getter or field named 'body'.dartundefined_getter
My code is:
onPressed: () async {
Response response;
Dio dio = new Dio();
String url =
'http://192.168.15.5:8090/api/getOs';
response = await dio.post(url, data: {
"numeroos": _numeroOsController.text
});
final extractedData = json.decode(response.body) //Here is the error
as Map<String, dynamic>;
final List<ProdutoOs> loadedProducts = [];
extractedData.forEach((key, value) {
loadedProducts.add(ProdutoOs(
cod_produto: value['Codigo_Produto'],
qtd: value['Qtde'],
desc: value['Descricao'],
numOs: value['Numero_da_OS'],
codOs: value['CodOS']));
Navigator.pop(context, true);
});
}
So i'm trying to put the response.body in a List but i cant, what am i doing wrong?
I have also tried using response.data and dont get the same error, the app runs but i get:
E/flutter (11379): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'String'
Maybe try this:
List responseElements = jsonDecode(response.body);
responseElements.map((singleJsonObject) => {
// do your parsing here
});
Add the await keyword when you're parsing the url
add await before parsing the url

Get data from JSONArray

I'm trying to parse data from my json with the following kotlin code:
val text = JSONObject(URL(request).readText())
val results = text.getJSONArray("results")
val name = results.getJSONObject(5).getString("name") // org.json.JSONException: Index 5 out of range [0..1)
json
{
summary: {
queryType: "NEARBY",
queryTime: 13,
numResults: 2,
offset: 0,
totalResults: 2,
fuzzyLevel: 1,
geoBias: {
lat: -37.736343,
lon: 145.152114
}
},
results: [
{
type: "POI",
id: "AU/POI/p0/77255",
score: -0.38554,
dist: 385.5365152133808,
info: "search:ta:0323405846509-AU",
poi: {
name: "La Gourmet",
However I'm getting the following error on my 3rd line:
org.json.JSONException: Index 5 out of range [0..1)
I'm not sure why I'm getting this error. I resorted to searching for name via index because .getJSONObject("poi") doesn't take a String. This is also concerning because the data may change so I would prefer to query the JSON via String.
Any idea?
results is an array, and your code tries to get the 5th element of the array. You need to get the first element, and then you can get poi by name.
val text = JSONObject(URL(request).readText())
val results = text.getJSONArray("results")
val result0 = results.getJSONObject(0)
val poi = result0.getJSONObject("poi")

Categories

Resources