在 POST 请求的 Body Flutter 中添加完整的 JSON 数据

问题描述 投票:0回答:2

我希望每个人都一切都好。我正在使用

POST
发出
HTTPClient
请求并发布表单数据。以前我只在请求正文中传递了三个字段,并且所有这三个字段值都已成功发布,但现在我想添加正文中的所有字段,但要添加的字段太多,所以我想添加整个
JSON 
体内数据。

我使用

Postman
获取整个
JSON
数据,并使用
quicktype.io
工具将其解析为模型类,我已将其作为参数传递给函数以及请求主体。

但是我完全不确定代码,因为我是 Flutter 和 API 的新手,而且我在访问 UI 页面中的功能时也遇到了问题。

任何人都可以帮助我解决这里的错误吗?

API_Manager 类:

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;
    }
  }

用户界面代码:

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;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  }

添加ContactModel类:

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
json flutter rest dart post
2个回答
4
投票

我希望你一切都好 你可以使用这个代码

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 ;

  }

你可以这样使用:

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

0
投票

{“数据”:{“companyId”:“56”,“appVersion”:10},“令牌”:“PIjJNOtW%2FKwkRYo0LIC%2Fzv8kWggswanhaFA1I91FwSYc6Yvvnzn6u7gPD69nYEgFFPECsLWgs6YRKBfSCDgc82wMjB5u8gWJVs3qU 8JBxDTQ3d1h4b0AZRxeOSoMDg7iCcKOjXUcPrStvxbdvfQoCBDQDqpX1HJDQ1jhdkxwaxY%3D"}如何在flutter dart中传递它

© www.soinside.com 2019 - 2024. All rights reserved.