length of server response in flutter http package - flutter

I am using future builder for building list view. I am getting the response from server. I am getting exactly what i need. There is single error that i am trying to resolve. The error is when i fetch data from server using http.get method : String data=response.body; I am getting the right response that i want and i am parsing it as String catagoeryId=jsonDecode(data)["data"][i]["_id"];
Now the problem i faced when i decode this json i passed this String inside my constructor using for loop. But i have to give length to stop for loop. the length i am using is: data.length. It decode my json response and passes inside my constructor. But after the json length end its stop working and crashed. I checked the length of data.length its something around 344. But i am having only 3 objects. Here is the code i am using for parsing:
Future<List<ProductCatagoery>> getCatagories()async{
http.Response response = await http.get("http://138.68.134.226:3020/api/category/");
List<ProductCatagoery> products=[];
String data=response.body;
for (int i=0;i<=data.length;i++) {
String catagoeryId=jsonDecode(data)["data"][i]["_id"];
String catagoeryThumb=jsonDecode(data)["data"][i]["thumb"];
String catagoeryName=jsonDecode(data)["data"][i]["name"];
bool catagoeryActive=jsonDecode(data)["data"][i]["active"];
print('name is: $catagoeryId : $catagoeryThumb : $catagoeryName : $catagoeryActive');
ProductCatagoery newUser=
ProductCatagoery(catagoeryId,catagoeryThumb,catagoeryName,catagoeryActive);
products.add(newUser);
print('added ${newUser.id}');
print('length is${products.length}');
print('last length data: ${data.length}');
}
return products;
}
Model class:
class ProductCatagoery {
final String id;
final String thumb;
final String name;
final bool active;
ProductCatagoery(this.id,this.thumb,this.name,this.active);
}
Response is:
{"success":true,"data":[{"_id":"5f13cc94c63abc03522eff41","thumb":"category/fresh-meat.jpg","name":"Fresh Meat","active":true},{"_id":"5f13cc73c63abc03522eff40","thumb":"category/fruits-vegetables.jpg","name":"Fruits & Vegetables","active":true},{"_id":"5f13cca5c63abc03522eff42","thumb":"category/grocery.jpg","name":"Grocery","active":true}]}
Note: I just need String data=response.body; data length. I am not using an map etc. I also showed products in list if i return product list after 1, 2 or 3th iteration.

First, decode the response received
final responseFormat = json.decode(response.body);
Then, you can get the list you want to loop with this
final data = responseFormat["data"];
Finally, you can get the length of the list : data.length.
Full code
List<ProductCatagoery> products = [];
final responseFormat = json.decode(response.body);
final data = responseFormat["data"];
for (int i = 0; i < data.length; i++) {
String catagoeryId = data[i]["_id"];
String catagoeryThumb = data[i]["thumb"];
String catagoeryName = data[i]["name"];
bool catagoeryActive = data[i]["active"];
print(
'name is: $catagoeryId : $catagoeryThumb : $catagoeryName : $catagoeryActive');
ProductCatagoery newUser = ProductCatagoery(
catagoeryId, catagoeryThumb, catagoeryName, catagoeryActive);
products.add(newUser);
print('added ${newUser.id}');
print('length is${products.length}');
print('last length data: ${data.length}');
}

Related

Flutter - loop not working while parsing json

I am trying to create model and parse json data from api
for that i created the model class you can see below
class FeatureModel {
String? PlanFeatures;
bool? FeatureStatus;
FeatureModel({this.PlanFeatures, this.FeatureStatus});
FeatureModel.fromJson(parsonJson) {
PlanFeatures = parsonJson['PlanFeatures'];
FeatureStatus = parsonJson['FeatureStatus'];
}
}
now i am trying to parse json with the help of loop
let me show you my method
List<FeatureModel> featureModel = [];
Uri featureAPI = Uri.parse(
planFeatureApi);
apiCall() async {
try {
http.Response response = await http.get(featureAPI);
// print(response.statusCode);
if (response.statusCode == 200) {
var decode = json.decode(response.body);
print(decode);
for (var i = 0; i < decode.length; i++) {
print(i);
featureModel.add(
FeatureModel.fromJson(decode[i]),
);
}
}
} catch (e) {}
}
I am calling it here
onPressed: () async{
await apiCall();
}
but the problem is here
loop is not working while parsing data
in that particular code i remains on 0 only
when i removes featureModel.add( FeatureModel.fromJson(decode[i]), ); i started increaing till 10
please let me know if i am making any mistake or what
thanks in advance
Here is the sample of api respone
[{"PlanFeatures":"Video Link Sharing","FeatureStatus":"true"},{"PlanFeatures":"Email \u0026amp; Telephonic Support","FeatureStatus":"true"},{"PlanFeatures":"Remove Pixeshare Branding","FeatureStatus":"false"},{"PlanFeatures":"Add Custom logo on uploaded photos","FeatureStatus":"false"},{"PlanFeatures":"Get Visitor Info","FeatureStatus":"false"},{"PlanFeatures":"Mobile Apps","FeatureStatus":"false"},{"PlanFeatures":"Send Questionnaries","FeatureStatus":"false"},{"PlanFeatures":"Create \u0026amp; Send Quotation","FeatureStatus":"false"},{"PlanFeatures":"Online Digital Album Sharing","FeatureStatus":"false"},{"PlanFeatures":"Analytics","FeatureStatus":"false"}]
thanks
I found many errors, first, the fromJson is not a factory constructor and doesn't return a class instance from the JSON.
the second one is that the bool values from the sample you added are String not a bool so we need to check over it.
try changing your model class to this:
class FeatureModel {
String? PlanFeatures;
bool? FeatureStatus;
FeatureModel({this.PlanFeatures, this.FeatureStatus});
factory FeatureModel.fromJson(parsonJson) {
return FeatureModel(
PlanFeatures: parsonJson['PlanFeatures'],
FeatureStatus: parsonJson['FeatureStatus'] == "false" ? false : true,
);
}
}

how to convert json string in dart flutter?

I have string response like this, I got only below response of my api.
{authToken: msadnmsandnasdn}
and I have to convert as below.
{"authToken": "msadnmsandnasdn"}
So how i can do this please Help me.
You can use various manipulation operations to do that manually:
import 'dart:convert';
void main() {
var s = "{authToken: msadnmsandnasdn, name:risheek}";
var kv = s.substring(0,s.length-1).substring(1).split(",");
final Map<String, String> pairs = {};
for (int i=0; i < kv.length;i++){
var thisKV = kv[i].split(":");
pairs[thisKV[0]] =thisKV[1].trim();
}
var encoded = json.encode(pairs);
print(encoded);
}
Output:
{"authToken":"msadnmsandnasdn"," name":"risheek"}
You need to use jsonDecode on that string like this:
var response = {authToken: msadnmsandnasdn....};
var result = jsonDecode(response);

Remove column name after get data

So when I get some string data from database I'm using this method
var res = "";
Future<void> cetak(String query) async {
var req = await SqlConn.readData(query);
setState(() {
res = req;
});
}
then im using method cetak() like this
cetak("SELECT CUST_NAME FROM ts_custxm WHERE CUST_CODE = '$custCode'");
But when im trying to display the res using Text(res)
it show [{"CUST_NAME":"MY NAME"}]
any idea how to make res only show MY NAME without show its column name?
You first need to convert by jsonDecode() or json.decode():
var req = jsonDecode(req)
setState(() {
res = req;
});
and then access to your data by:
res[0]["CUST_NAME"].toString()
You are getting result of a query in res variable. As a result of a query is an array of objects.
in your case : [{"CUST_NAME":"MY NAME"}]
so get MY NAME you should use res[0]["CUST_NAME"].toString().
Hope this will help!

How to call a List with Strings to make the call dynamic

I'm searching for create a dynamic form which contain DropDownButtons.
Before do that, I'm trying something on DartPad to know if it's possible to call a list with some Strings.
Below an example about what I want to do (maybe what I'm searching for is now possible) :
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},
{"name": "5A"}
];
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(listOfType);
}
In this case it print "listOf3AInitial" and I want to print the List {"name": "4A"},{"name": "5A"}.
How it is possible to do that ?
Regards
You have to map a string of it's value to do so. For example
List<Map<String, String>> listOf3AInitial = [{"name": "4A"}, {"name": "5A"}];
Map<String, List<Map<String, String>>> list3AInitialMap = {
"listOf3AInitial" : listOf3AInitial,
};
Now you can get a value from this map like
String _listOf = "listOf";
String _year = "3A";
String _type = "Initial";
var listOfType = "$_listOf$_year$_type";
print(list3AInitialMap[listOfType]);
Your var listOfType returns a String. Unfortunately, you cannot use/convert String as a variable name.
In this case, you may want to use a map:
void main() {
List<Map<String, String>> listOf3AInitial = [{"name": "4A"},{"name": "5A"}];
List<Map<String, String>> listOf3BInitial = [{"name": "4B"},{"name": "5B"}];
String _listOf = "listOf";
String _yearA = "3A"; //A
String _yearB = "3B"; //B
String _type = "Initial";
//Reference your lists in a map
Map<String, dynamic> myLists = {
"listOf3AInitial": listOf3AInitial,
"listOf3BInitial": listOf3BInitial
};
//This returns your listOf3AInitial
var listOfType = myLists["$_listOf$_yearA$_type"];
print(listOfType);
//You may also access it directly
print(myLists["$_listOf$_yearB$_type"]);
}

How to convert a list of numbers in a String to a list of int in dart

After reading a line from a file, I have the following String:
"[0, 1, 2, 3, 4]"
What is the best way to convert this String back to List<int>?
Just base on following steps:
remove the '[]'
splint to List of String
turn it to a int List
Sth like this:
List<int> list =
value.replaceAll('[', '').replaceAll(']', '')
.split(',')
.map<int>((e) {
return int.tryParse(e); //use tryParse if you are not confirm all content is int or require other handling can also apply it here
}).toList();
Update:
You can also do this with the json.decode() as #pskink suggested if you confirm all content is int type, but you may need to cast to int in order to get the List<int> as default it will returns List<dynamic> type.
eg.
List<int> list = json.decode(value).cast<int>();
You can convert String list to int list by another alternate method.
void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
stringList.map((e){
var intValue = int.tryParse(e);
intList.add(intValue!);
print(intList);
});
print(a);
}
Or by using for in loop
void main() {
List<String> stringList= ['1','2','3','4'];
List<int> intList = [];
for (var i in stringList){
int? value = int.tryParse(i);
intList.add(value!);
print(intList);
}
}