Shreyas Bhardwaj
Shreyas Bhardwaj

Reputation: 81

Add entire JSON Data in POST Request's Body Flutter

I hope everyone's doing fine. I'm making a POST request using HTTPClient and posting a form's data. Previously I had passed only three fields in the requests body and all those three fields values are being posted successfully but now I want to add all the fields in the body but there are just too many to add so I thought of adding the entire JSON data in the body.

I've used Postman to get the entire JSON data and used quicktype.io tool to parse it into a model class which I've passed as parameters to the function and also to the requests body.

But I'm not sure of the code entirely as I'm new to flutter and working with API's and I'm also having trouble accessing the function in the UI page.

Can anyone help me out with my mistakes here?

API_Manager class:

Future<AddContactModel> addContact(AddContactModel contact) async {
    var client = http.Client();
    String addContactUrl =
        "https://example.com/ma/api/contacts/new";
    String basicAuth = 'Basic examplebasicauthkey';
    var response = await client.post(addContactUrl,
        headers: <String, String>{
          'authorization': basicAuth,
          "Accept": "application/json",
          "Content-Type": "application/x-www-form-urlencoded",
        },
        body: contact.toJson());    //from the Model class
    // print(response.statusCode);
    developer.log(response.body);
    if (response.statusCode == 201) {
      final String responseString = response.body;
      return addContactModelFromJson(responseString);
    } else {
      return null;
    }
  }

UI Code:

Future saveContact() async {         //Old function, needs to be changed with new parameters and body
    final String firstName = _firstName.text;   
    final String lastName = _lastName.text;
    final String email = _email.text;

    final AddContactModel contact =
        await API_Manager().addContact(firstName, lastName, email);    //Error here, need to pass the model but dont know how.

    setState(() {
      _contact = contact;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Form(
        key: _formKey,
        autovalidateMode: AutovalidateMode.onUserInteraction,
        child: Scaffold(
          appBar: AppBar(
            title: Text('Add Contact'),
            actions: <Widget>[
              FlatButton(
                textColor: Colors.white,
                onPressed: () async {
                  // Validate returns true if the form is valid, or false otherwise.
                  if (_formKey.currentState.validate()) {
                    await saveContact();
                  }
                },
                child: Text(
                  'SAVE',
                  style: TextStyle(
                    fontSize: 18,
                    color: Colors.white,
                    fontWeight: FontWeight.w600,
                  ),
                ),
                shape:
                    CircleBorder(side: BorderSide(color: Colors.transparent)),
              )
            ],
          ),
          body: SingleChildScrollView(
            child: Container(
              margin: EdgeInsets.all(5),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _contact == null
                      ? Container()
                      :
                      //Text("The user ${_contact.contact.fields.all.firstname} is created successfully at time ${_contact.contact.lastActive.toIso8601String()}"),
                      TextFormField(
                          onSaved: null,
                          controller: _ipCountryCode,
                          keyboardType: TextInputType.text,
                          decoration: InputDecoration(
                              labelText: 'IP Country Code',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                        ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DateTimeFormField(
                          decoration: InputDecoration(
                              labelText: 'Time First Seen',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          onDateSelected: (DateTime value) {
                            setState(() {
                              timeFirstSeen = value;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _eventRevenue,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Event Revenue',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _sendsSinceLastEngagement,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Sends since last engagement',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _marketingEmailsOpened,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Marketing Emails Opened',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DateTimeFormField(
                          decoration: InputDecoration(
                              labelText: 'Last marketing email click date',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          onDateSelected: (DateTime value) {
                            setState(() {
                              lastMarketingEmailClickDate = value;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Email Address Quarantined',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: emailAddressQuarantined,
                          onChanged: (newValue) {
                            setState(() {
                              emailAddressQuarantined = newValue;
                            });
                          },
                          items: emailAddressQuarantinedItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _socialAwarenessClicks,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Social Awareness Clicks',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          decoration: InputDecoration(
                              labelText: 'Lead Status',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: leadStatus,
                          onChanged: (newValue) {
                            setState(() {
                              leadStatus = newValue;
                            });
                          },
                          items: leadStatusItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DateTimeFormField(
                          decoration: InputDecoration(
                              labelText: 'Create date',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          onDateSelected: (DateTime value) {
                            setState(() {
                              createDate = value;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  }

addContactModel class:

import 'dart:convert';

AddContactModel addContactModelFromJson(String str) => AddContactModel.fromJson(json.decode(str));

String addContactModelToJson(AddContactModel data) => json.encode(data.toJson());

class AddContactModel {
  AddContactModel({
    this.contact,
  });

  Contact contact;

  factory AddContactModel.fromJson(Map<String, dynamic> json) => AddContactModel(
    contact: Contact.fromJson(json["contact"]),
  );

  Map<String, dynamic> toJson() => {
    "contact": contact.toJson(),
  };
}

class Contact {
  Contact({
    this.isPublished,
    this.dateAdded,
    this.dateModified,
    this.createdBy,
    this.createdByUser,
    this.modifiedBy,
    this.modifiedByUser,
    this.id,
    this.points,
    this.color,
    this.fields,
    this.lastActive,
    this.owner,
    this.ipAddresses,
    this.tags,
    this.utmtags,
    this.stage,
    this.dateIdentified,
    this.preferredProfileImage,
    this.doNotContact,
    this.frequencyRules,
  });

  bool isPublished;
  DateTime dateAdded;
  dynamic dateModified;
  int createdBy;
  String createdByUser;
  dynamic modifiedBy;
  dynamic modifiedByUser;
  int id;
  int points;
  dynamic color;
  Fields fields;
  dynamic lastActive;
  dynamic owner;
  List<dynamic> ipAddresses;
  List<dynamic> tags;
  dynamic utmtags;
  dynamic stage;
  dynamic dateIdentified;
  dynamic preferredProfileImage;
  List<dynamic> doNotContact;
  List<dynamic> frequencyRules;

  factory Contact.fromJson(Map<String, dynamic> json) => Contact(
    isPublished: json["isPublished"],
    dateAdded: DateTime.parse(json["dateAdded"]),
    dateModified: json["dateModified"],
    createdBy: json["createdBy"],
    createdByUser: json["createdByUser"],
    modifiedBy: json["modifiedBy"],
    modifiedByUser: json["modifiedByUser"],
    id: json["id"],
    points: json["points"],
    color: json["color"],
    fields: Fields.fromJson(json["fields"]),
    lastActive: json["lastActive"],
    owner: json["owner"],
    ipAddresses: List<dynamic>.from(json["ipAddresses"].map((x) => x)),
    tags: List<dynamic>.from(json["tags"].map((x) => x)),
    utmtags: json["utmtags"],
    stage: json["stage"],
    dateIdentified: json["dateIdentified"],
    preferredProfileImage: json["preferredProfileImage"],
    doNotContact: List<dynamic>.from(json["doNotContact"].map((x) => x)),
    frequencyRules: List<dynamic>.from(json["frequencyRules"].map((x) => x)),
  );

  Map<String, dynamic> toJson() => {
    "isPublished": isPublished,
    "dateAdded": dateAdded.toIso8601String(),
    "dateModified": dateModified,
    "createdBy": createdBy,
    "createdByUser": createdByUser,
    "modifiedBy": modifiedBy,
    "modifiedByUser": modifiedByUser,
    "id": id,
    "points": points,
    "color": color,
    "fields": fields.toJson(),
    "lastActive": lastActive,
    "owner": owner,
    "ipAddresses": List<dynamic>.from(ipAddresses.map((x) => x)),
    "tags": List<dynamic>.from(tags.map((x) => x)),
    "utmtags": utmtags,
    "stage": stage,
    "dateIdentified": dateIdentified,
    "preferredProfileImage": preferredProfileImage,
    "doNotContact": List<dynamic>.from(doNotContact.map((x) => x)),
    "frequencyRules": List<dynamic>.from(frequencyRules.map((x) => x)),
  };
}

class Fields {
  Fields({
    this.core,
    this.social,
    this.personal,
    this.professional,
    this.all,
  });

  All core;
  Social social;
  List<dynamic> personal;
  List<dynamic> professional;
  All all;

//Not the full code

Upvotes: 1

Views: 565

Answers (1)

mohammad mobasher
mohammad mobasher

Reputation: 777

i hope you be fine you can use this code

Future<http.Response> post(String url, {Map<String, dynamic> body}) async {
    // try {
    var token = "AccessToken";
    final response = await http.post(_baseUrl + url,
        headers: {
          "Authorization": 'Bearer ' + token,
          "Accept": "application/json"
        },
        body: body);
     return response ;

  }

and you can use like this :

post(url, body: your_model.toJson());

Upvotes: 4

Related Questions