0
  1. Says I created a ListView.Builder.
  2. I have an "Add Job" button to add job(s) to the list.
  3. And lets I have now added 2 jobs in the list. I want to submit this array data through API.
  4. My problem is how to encode array of map and pass them properly?
  5. This image describes what I'm trying to tell.
  6. 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: () {}),
        ])
Mong
  • 55
  • 1
  • 5
  • Check it out [this answer](https://stackoverflow.com/a/55025048/7742857). They look like similar – ismail Apr 02 '20 at 16:45

2 Answers2

0
 String jsonEncodedString=json.encode(value);

value can be object of anything like list,map, int,string,double,etc example:

 String jsonEncodedString=json.encode({'hello':'i am a map'});

you can pass the json encoded string through API

Sasi Zets
  • 11
  • 1
  • I am still kinda confused, Sasi Zets, do you mind guiding me the also what changes I should do in my POST method as well? – Mong Apr 03 '20 at 03:52
0

Solution:

  1. I need to return an encoded json array when I call API. Hence, I need to encode 'data'.
createOccupations(int id, var data)async{
var _sectorsUrl = '$_hostUrl/occupations';
final _response = await post(
 _sectorsUrl,
 body: jsonEncode({"batch":data}), //jsonEncode to encode the data to json
 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);
}
}
  1. Create the function to call API when user trigger button.
void _createJobs() {
    setState(() {
      List<Batch> _listBatch = List<Batch>();
      var newList;
      for (var i = 0; i < jobCount; i++) {
        Batch _batch = Batch(sector_id:_sectorIdController[i].text,company: _companyNameController[i].text);
        _listBatch.addAll([_batch]);
      }
      newList = _listBatch;
      _jobAPI.createOccupation(context, newList); // I do not need to encode the data here because when I pass it, I already did encoding as show above.
    });
  }
Mong
  • 55
  • 1
  • 5