Shreyas Bhardwaj
Shreyas Bhardwaj

Reputation: 81

HTTP POST request in Flutter

Hi I hope everyone's doing fine, I'm new to flutter building my first application and I have to add a contact in flutter using RestAPI. The problem is I'm not getting any right way to do it.

I'm using HTTP Client and the response status code is supposed to be 201, I am successfully getting this response when I call my addContact() function in the Main class but not when I call it in the add_contacts class.

I have successfully created the model also using quicktype.io tool and in the UI part I have a form and for now I've created it in such a way that when I click on save, it shows a container with text that my contact is saved but since I'm not getting the response only in that class I can't verify also whether the contact is saved or not.

Also I don't know how to actually post all the contact details from the form, I've added all the necessary controllers and everything but I want to post all the contact details when I click on save.

According to my API Documentation I can post any contact field alias as a parameter. For example, firstname, lastname, email, etc.

I'm hoping someone could guide me through this, all the codes I have attached below. Thank You.

API_Manager class:

Future<AddContactModel> addContact(
    String firstName,
    String lastName,
    String email,
  ) async {
    var client = http.Client();
    String addContactUrl =
        "https://example.com/ma/api/contacts/new";
    String basicAuth = 'Basic exampleauthkey';
    var response = await client.post(addContactUrl, headers: <String, String>{
      'authorization': basicAuth,
      "Accept": "application/json",
    }, body: {
      "firstname": firstName,
      "lastname": lastName,
      "email": email
    });
    print(response.statusCode);
    //developer.log(response.body);
    if (response.statusCode == 201) {
      final String responseString = response.body;
      return addContactModelFromJson(responseString);
    } else {
      return null;
    }
  }

add_contact class:

class _AddContactsState extends State<AddContacts> {
  AddContactModel _contact;
  TextEditingController _ipCountryCode,
      _eventRevenue,
      _sendsSinceLastEngagement,
      _marketingEmailsOpened,
      _socialAwarenessClicks,
      _firstName,
      _lastName,
      _email,
      _reasonForEmailUnsubscribe;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String contactOwner,
      stage,
      leadStatus,
      tags,
      emailAddressQuarantined,
      selectCompany;
  DateTime timeFirstSeen,
      lastMarketingEmailClickDate,
      createDate,
      becameAnEvangelistDate;
  List contactOwnerItem = [
    "example owner 1",
    "example owner 2",
    "example owner 3",
    "example owner 4"
  ];
  List stageItem = [
    "Stage 1",
    "Stage 2",
    "Stage 3",
    "Stage 4",
  ];
  List leadStatusItem = [
    "Status 1",
    "Status 2",
    "Status 3",
    "Status 4",
  ];
  List tagsItem = [
    "tag1",
    "tag2",
    "tag3",
    "tag4",
  ];
  List emailAddressQuarantinedItem = ["On", "Off"];
  List selectCompanyItem = ["Company 1", "Other"];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _ipCountryCode = TextEditingController();
    _eventRevenue = TextEditingController();
    _sendsSinceLastEngagement = TextEditingController();
    _marketingEmailsOpened = TextEditingController();
    _socialAwarenessClicks = TextEditingController();
    _firstName = TextEditingController();
    _lastName = TextEditingController();
    _reasonForEmailUnsubscribe = TextEditingController();
    _email = TextEditingController();
  }

  Future saveContact() async{
    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);

    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: () {
                  // Validate returns true if the form is valid, or false otherwise.
                  if (_formKey.currentState.validate()) {
                    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 and was last active 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;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DateTimeFormField(
                          decoration: InputDecoration(
                              labelText: 'Became an evangelist date',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          onDateSelected: (DateTime value) {
                            setState(() {
                              becameAnEvangelistDate = value;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _firstName,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'First Name',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _lastName,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Last Name',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    //validator: validateEmail,
                    onSaved: null,
                    controller: _email,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Email',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _reasonForEmailUnsubscribe,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Reason for email unsubscribe',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Tags',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: tags,
                          onChanged: (newValue) {
                            setState(() {
                              tags = newValue;
                            });
                          },
                          items: tagsItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Select a company',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: selectCompany,
                          onChanged: (newValue) {
                            setState(() {
                              selectCompany = newValue;
                            });
                          },
                          items: selectCompanyItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Contact Owner',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: contactOwner,
                          onChanged: (newValue) {
                            setState(() {
                              contactOwner = newValue;
                            });
                          },
                          items: contactOwnerItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          decoration: InputDecoration(
                              labelText: 'Stage',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: stage,
                          onChanged: (newValue) {
                            setState(() {
                              stage = newValue;
                            });
                          },
                          items: stageItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  }

I've given all static data to the DropdownButtonFormField for now, but I need to populate it with the api response, please help me achieve that too.

Here's how my UI for the form looks: enter image description here

Upvotes: 0

Views: 2314

Answers (1)

DonnC
DonnC

Reputation: 67

there are many questions here you have given but forasync code try adding the await

onPressed: () async {
    // Validate returns true if the form is valid, or false otherwise.
    if (_formKey.currentState.validate()) async {
       await saveContact();
       }
   },

to send all the form data to your server, just add more fields as you have done here, from the textcontrollers you have defined

// add all fields you want to post to server here
final AddContactModel contact = await  API_Manager().addContact(firstName, lastName, email, ..);

Upvotes: 2

Related Questions