I integrated API, I want to get both key and value from API response. I stored both key and value in two separate arrays and display inside the listview.so How to get key and value from api response.
[
{ "Name": "abc"
"Department": "Marketing",
"EmpCode": "ABC123",
"Salary":"20000",
"Pincode": 100023
}]
I got response using this code:
List list = json.decode(response.body);
So how to get Name,department,empcode and abc,marketing separate.
just use a forEach loop and it will extract keys and values for you which you can store according to your requirement and you don't have to worry about how many keys you have
response.forEach((key, value){
print('key is $key');
print('value is $value ');
}
Create a class that will hold your fields and add a fromJson method like so:
class ClassName{
ClassName(
{this.Name,
this.Department,
this.EmpCode,
this.Salary,
this.Pincode,
});
String Name;
String Department;
String EmpCode;
double Salary;
String Pincode;
ClassName.fromJson(Map<String, dynamic> json) {
Name= json['Name'];
Department= json['Department'];
EmpCode= json['EmpCode'];
Salary= json['Salary'];
Pincode= json['Pincode'];
}
}
And then you could do something like that with your json that you get from the API:
var x = json.decode(response.body.toString());
var className = ClassName.fromJson(x);
Related
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"]);
}
I am testing flutter graphql for first time. Here is my query and variables that I am using graphql explorer.
My question is before I pass the query and queryVariables, I need to replace 1001 in queryVariables with parameter value. May I know how I can replace it?
const String query = r'''
query Albums($where: AlbumWhereInput) {
albums(where: $where) {
id
title
artist {
name
}
}
}
''';
const String queryVariables = r'''
{
"where": {
"artist_id": 1001
}
}
''';
Future<QueryResult> performQuery(String query,
{required Map<String, dynamic> variables}) async {
QueryOptions options =
QueryOptions(document: gql(query), variables: variables);
final result = await _client.query(options);
return result;
}
You haven't specified what package you're using, so I can't be specific about what is the best way to do this. But generally, you can use something like string interpolation:
final artistId = 1001;
final queryVariables = '''
{
"where": {
"artist_id": $artistId
}
}
''';
Note how we're using a normal string using ''' and not a raw string (r''') to be able to interpolate via $.
I have a class which has named constructor and I want to pass variable and eval the result as a class variable how can I achieve it like in javascript we have object literals and eval
I'm getting the data from server like [{path: 'fullName', msg: "Field is Required" }, {...}]
below is the example:
class Test{
String fullName;
Test({this.fullName});
}
Map ob = {fullName: "someAnotherName", another:another};
var t = Test(ob); //how to achieve this line
var varaible = "fullName";
t.[variable]; //how to achieve this line
`
It is common to write a named fromJson factory constructor which accpets a Map<String, dyanmic> as an argument which is the json data you will pass to it.
For the code you provided it would be like:
class Test{
String fullName;
Test({this.fullName});
factory Test.fromJson(Map<String, dynamic> json) {
return Test(
fullName: json['fullName'],
);
}
}
Map ob = {fullName: "someAnotherName", another:another};
var t = Test.fromJson(ob);
t.fullName;
Since your ob is a Map you can get fullname by writing
var name = ob['fullName'] or this way
var fullName = 'fullName';
var name = ob[fullName];
Both should contain someAnotherName
I have a JSON having some data as an array , and I wanna add
new data to JSON
This is My JSON structure
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID"
}
]```
I want to add new data so it can be like this
```[
{
"id":"JKT020",
"origin_time":"2020-06-30 12:00",
"location":"Jakarta, ID",
"flag":1
}
]```
Is it possible ? If it is can anyone tell me how to do that ? Thanks in advance.
And this is what I've been doing so far..
List data = json.decode(response.body);
for (int i = 0; i < data.length; i++) {
data.add(data[i]["flag"]=1);
print("object : " + data[i].toString());
}
});
It was printed like I want it, but return error in add line
The error said NoSuchMethodError: Class 'String' has no instance method '[]='
First of all, you have to Decode the JSON
var data=json.decode("Your JSON")
Now this is available as a list and map so you can add fields like
data[key]=value;
after that, you have to Encode it using json.encode
var data1=json.encode(data);
`
It's a good idea to get the JSON formatted and mapped to a Model. This will not only help to do null checks but also increase the readability of your code.
You can use a simple Model like
class myModel {
String id;
String originTime;
String location;
int flag;
myModel({this.id, this.originTime, this.location, this.flag});
myModel.fromJson(Map<String, dynamic> json) {
id = json['id'];
originTime = json['origin_time'];
location = json['location'];
flag = json['flag'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['id'] = this.id;
data['origin_time'] = this.originTime;
data['location'] = this.location;
data['flag'] = this.flag;
return data;
}
}
My problem is that I have a list of the following class:
class ingreso_Egreso_Dummy{
int tipo;
String monto;
String moneda;
String descripcion;
}
then I want to insert the data into a Map which later will be converted into a json and which I am creating like this:
Map<String, dynamic> body;
body = {
"Cod_Prom": "01",
"CodCli": "003526",
"Status": _index_status.toString(),
"NOMBRE": controller_nombre.text,
"APELLIDOS": controller_apellidos.text,
"solicitud":[{
"Cod_Solicit": 1.toString(),
"Fecha": DateFormat("y-d-M").format(DateTime.now()),
"Status_Solicit": "E",}],
"prestamo":[{
"Monto_Solicit":controller_monto_solic.text,
"Plazo":controller_plazo.text,
"Cod_TipoPlazo":_index_tipoplazo.toString(),
"Nombre_Resp":controller_nombreresp.text,
"Telf_Resp":controller_telefonoresp.text,}],
"Ingresos": [{
//// here I want create a loop that returns a map for each value
//// of the list like this:
//// "Descripcion": Listaingresos[i].descripcion;
})
}]
};
Every help is very appreciated, thank you.
// camelCaseStyle is a standard for class names for Dart
class IngresoEgresoDummy {
int tipo;
String monto;
String moneda;
String descripcion;
Map<String, dynamic> toJson(){
return {
'tipo': tipo,
'monto': monto,
'monedo': moneda,
'descripcion': descripcion
};
}
}
and after that
List<IngresoEgresoDummy> listaingresos= List();
Map<String, dynamic> body = {
// all your params
"Ingresos": listaingresos.map((ingreso) => ingreso.toJson()).toList()
// all your params
};