Parsing using For in String jsonString = await _ChieseAsset(); - json

Yo ,, during my experience of flutter i'll try to show on map marker saved into Json file..in this way i retrive only one of row
Future<chiese> loadChiese() async {
await wait(5);
String jsonString = await _ChieseAsset();
final jsonResponse = json.decode(jsonString);
for ( var i=0; i < 5; i++ ){
print(i);
return new chiese.fromJson(jsonResponse[i]);
}
}
Unfortunally var i show only 0 value and don't scan into json retrive only first value
why???
if i use ...
Future<chiese> loadChiese() async {
await wait(5);
String jsonString = await _ChieseAsset();
final jsonResponse = json.decode(jsonString);
return new chiese.fromJson(jsonResponse);
}
Reciving error ...
[ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: type 'List' is not a subtype of type 'Map'
Any idea??? Thanks

Change this:
return new chiese.fromJson(jsonResponse);
Into this:
return new chiese.fromJson(jsonResponse[0]);

Related

I'm trying to make a simple app in flutter that fetches data from an API. However when I try running the code I get the following error

"Dart Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable' "
It says that the error is in the following line:
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}
For context, the entire code is this:
class _HomePageState extends State<HomePage> {
final List<Object> _objects = [];
Future<List<Object>> fetchData() async{
const String urlString = 'https://api.publicapis.org/entries';
final Uri url = Uri.parse(urlString);
var response = await http.get(url);
final List<Object> objects = [];
if(response.statusCode == 200){
var jsonObjects = json.decode(response.body);
print("Step 1");
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}
}
return objects;
}
Any help would be greatly appreciated. Thanks.
Main problem is that response.body is not a list of elements, and you are assuming it is. Instead of that, it's a "key" : "value" type of json object, which cannot be iterated.
The for (var e in collection) syntax is made to be used with an Iterable collection, and _InternalLinkedHashMap (and maps in general) are not iterables.
The solution is to parse the response properly. Check this link if you want to follow best practices for flutter development json parsing.
Your api response's body is a Map:
{"count":1425,
"entries":[
{"API":"AdoptAPet","Description":"Resource to help get pets adopted","Auth":"apiKey","HTTPS":true,"Cors":"yes","Link":"https://www.adoptapet.com/public/apis/pet_list.html","Category":"Animals"},
{"API":"Axolotl","Description":"Collection of axolotl pictures and facts","Auth":"","HTTPS":true,"Cors":"no","Link":"https://theaxolotlapi.netlify.app/","Category":"Animals"},
...
]
}
what you are looking for is a list, Try this:
var jsonObjects = json.decode(response.body["entries"]);
print("Step 1");
for(var jsonObject in jsonObjects){
objects.add(Object.fromJson(jsonObject));
}

how to filter Json data and use other methods | function | classes? How get Json data into list?

Future<List<AdMob>>getData() async {
final String url =
"https://raw.githubusercontent.com/awais939869/AdsJson/main/speedifypro.json";
http.Response response = await http.get(Uri.parse(url));
// http.Response response = await http.get(Uri.parse("https://raw.githubusercontent.com/Hammad46/app/main/admob.json"));
var jsonObject = json.decode(response.body);
List <dynamic> data = (jsonObject as Map<String, dynamic>)['AdMob'];
List <AdMob> listData = [];
for (int i=0; i<data.length; i++)
listData.add(AdMob.fromJson(data[i]));
return listData;
}
ERROR
E/flutter ( 6315): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List'
JSON data
{
"AdMob": {
"Banner": "true",
"Interstitial": "true"
}
}
AdMob is not a List. it's a map. so if you want your code to work without problem your JSON should be like following:
{
"AdMob": [
{
"Banner": "true",
"Interstitial": "true"
}
]
}

Flutter - type 'List<dynamic>' is not a subtype of type 'Map<dynamic, dynamic>'

I'm just new in flutter and I think this is a newbie question.
I'm trying to get the data that I call on my API and save it to my model but it's having an error type 'List' is not a subtype of type 'Map<dynamic, dynamic>'
Here is the copy of my model
class AdTemplate{
final int id;
final String filePath;
final String notification;
final String status;
final int whenAdded;
AdTemplate(
{this.id,
this.filePath,
this.notification,
this.status,
this.whenAdded});
factory AdTemplate.fromJson(Map<String, dynamic> json) {
return AdTemplate(
id: json['ID'],
filePath: json['FilePath'],
notification: json['Notification'],
status: json['Status'],
whenAdded: json['WhenAdded']
);
}
}
And this is my function
Future<AdTemplate> getActiveBannerNotif() async {
try {
String url = 'https://api/path/';
var res = await http.get(url);
final Map data = convert.jsonDecode(res.body);
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(data);
return template;
} else {
print('No data.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
This is the sample data that I get from the API
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]
API returns JSON array not json object so that is List not Map.
try :
if (res.statusCode == 200) {
print("Data Fetch!");
AdTemplate template = AdTemplate.fromJson(json.decode(utf8.decode(res.bodyBytes)));
return template;
}
You are receiving an array from your API and that causes the error. change as following to access a single element from array
Future<AdTemplate> getActiveBannerNotif() async {
try {
String url = 'https://api/path/';
var res = await http.get(url);
if (res.statusCode == 200) {
print("Data Fetch!");
final data = convert.jsonDecode(res.body);
AdTemplate template = AdTemplate.fromJson(data[0]);
return template;
} else {
print('No data.');
return null;
}
} catch (e) {
print(e);
return null;
}
}
Your api return a List
[{"ID":49,"FilePath":"20210903t171244.png","Notification":"ACT","WhenAdded":1630689165,"Status":"INA"}]
Try to get data like that: data[0] or data.first before convert into model

How to return list in Dart language

I my code I want to return categories name list and populate in list view by using dart. i use HTTP get request and can successfully print the Json data but when I loop the json data into list but it cannot and print(categoriesList.length); give me no result. any idea how to solve it
Future<List<Categories>> _getCategory() async {
var data = await http.get("https://thegreen.studio/ecommerce/E-CommerceAPI/E-CommerceAPI/AI_API_SERVER/Api/Category/ViewCategoryNameAPI.php");
var jsonData = json.decode(data.body);
print(jsonData);
List<Categories> categoriesList = [];
for(var c in jsonData)
{
Categories a = Categories(c["Name"]);
categoriesList.add(a);
}
print(categoriesList.length);
return categoriesList;
}

Extract Data from JSON Array in Flutter/Dart

This is the response from request.
var response = [{"id":4731},{"id":4566},{"id":4336},{"id":4333},{"id":4172},{"id":4170},{"id":4168},{"id":4166},{"id":4163},{"id":4161}];
How to extract ids and store in List of int using flutter.
I have try this code but not working.
Future<List<int>> fetchTopIds() async{
final response = await client.get('$_baseUrl/posts?fields=id');
final ids = json.decode(response.body);
return ids.cast<int>();
}
This should do what you want:
var intIds = ids.map<int>((m) => m['id'] as int).toList();
This is what I did when got "array of object" as response (I know I'm late. But it will help the next guy)
List list = json.decode(response.body);
if (response.body.contains("id")) {
var lst = new List(list.length);
for (int i = 0; i < list.length; i++) {
var idValue = list[i]['id'];
print(idValuee);
}
Here I attached a complete example of converting a list to JSON and then retrieve the List back from that JSON.
import 'dart:convert';
void main() {
List<int> a= [1,2,3]; //List of Integer
var json= jsonEncode(a); //json Encoded to String
print(json.runtimeType.toString());
var dec= jsonDecode(json); //Json Decoded to array of dynamic object
print(dec.runtimeType.toString());
a= (dec as List).map((t)=> t as int).toList(); //dynamic array mapped to integer List
print(a);
}
I found a better and easier way to get required information/ data from JSON Array.
Refer to https://pub.dev/packages/http/example to know more
Code to get a quick starts:
void main(List<String> arguments) async {
var url = 'ENTER YOUR API ENDPOINT';
var response = await http.get(url);
var jsonResponse = convert.jsonDecode(response.body);
var itemCount = jsonResponse['totalItems'];
print('Number of books about http: $itemCount.');
Here 'totalItems' would be your desired key.This will only work if you get a response.statusCode == 200