首页 > 解决方案 > 如何在 Flutter 中调用 POST 函数

问题描述

我正在使用和发布表单数据发出POST请求。HTTPClient当我尝试仅使用 3 个字段时请求成功,但现在我想添加所有字段,因此我在函数的参数主体中添加了完整的JSON对象模型POST

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

我在 UI 中有一个保存按钮,单击该按钮应发布所有表单数据,但我无法构建该函数saveContact()并从模型中获取字段并将其初始化为表单字段控制器

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

SAVE FUNCTION 调用 POST 请求的函数:

Future saveContact() async {  //Need to call function here, get Model fields 
                               //and initialize it to the controllers.
                               //await API_Manager().addContact(contact); 
                               //Something like this but sure of the full code
}

  @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)),
                  ),  
                 //Not the full code

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

标签: jsonflutterdartposthttp-post

解决方案


我有这个帖子请求,您可以根据自己的意愿更改

这是发布功能

    Future<ResponseModel> HTTPPOST<T>(String url, List<QueryModel> query,
    var body, HeaderEnum headerType, ResponseEnum responseType) async {
    try {
        var response = await http.post(
            UrlGenerator(url, query),
            headers: headerGetter(headerType),
            body: body,
        );

        return responseGetter<T>(responseType, response);
    } catch (e) {
        return ResponseModel(
            isSuccess: false,
            statusCode: "500",
            data: null,
            message: "خطایی در عملیات رخ داده است");
    }
}

这是 responseGetter 函数

responseGetter<T>(ResponseEnum typeEnum, http.Response response) {
    try {
        switch (typeEnum) {
            case ResponseEnum.ResponseModelEnum:
                String data = utf8.decode(response.bodyBytes);

                if (data == null || data.isEmpty)
                    return ResponseModel(
                        statusCode: "555",
                        isSuccess: false,
                        data: null,
                    );

                return ResponseModel().fromJson(
                    json.decode(data),
                );
            default:
                return response.bodyBytes;
        }
    } catch (e) {
        return ResponseModel(
            isSuccess: false,
            statusCode: "500",
            data: null,
            message: "خطایی در عملیات رخ داده است");
    }
}

这是在一个例子中使用 post 函数

Future<ResponseModel<CartHeader>> AddProduct(int productId, int qty) async {

var map = {"productId": productId, "qty": qty};

var json = jsonEncode(map);

var response = await HTTPPOST(
  RoutingCart.POST_AddProduct,
  [],
  json,
  HeaderEnum.BearerHeaderEnum,
  ResponseEnum.ResponseModelEnum,
);

return ResponseModel<CartHeader>(
  isSuccess: response.isSuccess,
  statusCode: response.statusCode,
  data: response.data,
  message: response.message,
); }

推荐阅读