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

Posted

技术标签:

【中文标题】在 POST 请求的 Body Flutter 中添加整个 JSON 数据【英文标题】:Add entire JSON Data in POST Request's Body Flutter 【发布时间】:2021-07-23 19:52:50 【问题描述】:

我希望每个人都做得很好。我正在使用HTTPClient 发出POST 请求并发布表单数据。以前我在请求正文中只传递了三个字段,所有这三个字段的值都已成功发布,但现在我想添加正文中的所有字段,但要添加的字段太多,所以我想添加整个 @987654323 @body 中的数据。

我使用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;
                            );
                          ,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  

addContactModel 类:

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

【问题讨论】:

【参考方案1】:

我希望你没事 您可以使用此代码

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());

【讨论】:

您好,感谢您的回答。你能告诉我我应该在这个函数中返回什么以及我应该如何调用它? 嘿,我知道了,但是调用方法saveContact()有问题,我不知道如何访问所有字段 你必须像这样转换 response.body json.decode(response.body.toString());

以上是关于在 POST 请求的 Body Flutter 中添加整个 JSON 数据的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 应用中监听和处理 POST 请求

如何将内存中的图像上传为 Flutter web 中 body 上的二进制图像?

获取post请求中body的内容

url包含端口时如何使用Flutter http请求?

为啥nodejs express post请求中的“body”为空?

Flutter dio不适用于flutter web中的post请求