- Says I created a ListView.Builder.
- I have an "Add Job" button to add job(s) to the list.
- And lets I have now added 2 jobs in the list. I want to submit this array data through API.
- My problem is how to encode array of map and pass them properly?
- This image describes what I'm trying to tell.
- Thank you so much in advance.
And this is the request body:
{"batch":
[
{"sector_id":1,"company":"Company"},
{"sector_id":2,"company":"Organization"},
......if has more
]
}
And I have this model:
class Occupations {
List<Batch> batch;
Occupations({this.batch});
Occupations.fromJson(Map<String, dynamic> json) {
if (json['batch'] != null) {
batch = new List<Batch>();
json['batch'].forEach((v) {
batch.add(new Batch.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.batch != null) {
data['batch'] = this.batch.map((v) => v.toJson()).toList();
}
return data;
}
}
class Batch {
int sectorId;
String company;
Batch({this.sectorId, this.company});
Batch.fromJson(Map<String, dynamic> json) {
sectorId = json['sector_id'];
company = json['company'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['sector_id'] = this.sectorId;
data['company'] = this.company;
return data;
}
}
My POST method:
createOccupations(int id, String company)async{
var _sectorsUrl = '$_hostUrl/occupations';
String _body ='{"batch":[{"sector_id":id,"company":"$company"}]}';
final _response = await post(
_sectorsUrl,
body: _body,
headers: {
'Content-type':'application/json',
'Accept':'application/json',
}
);
if (_response.statusCode==200) {
return Occupations.fromJson(json.decode(_response.body));
} else {
print(_response.statusCode);
print(_data);
}
}
And this is my UI:
Column(children: <Widget>[
Expanded(
child: ListView.builder(
itemCount: jobCount,
itemBuilder: (context, index) {
_sectorIdController.add(new TextEditingController());
_companyNameController.add(new TextEditingController());
return Container(
margin: margin10,
padding: padding10,
decoration: BoxDecoration(
border: Border.all(color:black)
),
child: Column(
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Sector Id'),
controller: _sectorIdController[index],
),
TextField(
decoration:
InputDecoration(labelText: 'Company Name'),
controller: _companyNameController[index]),
],
),
);
})),
RaisedButton(
child: Text('Add Job'),
onPressed: () {
setState(() {
jobCount++;
});
}),
RaisedButton(child: Text('Submit Occupations'), onPressed: () {}),
])