如何在 Flutter 中调用 POST 函数

Posted

技术标签:

【中文标题】如何在 Flutter 中调用 POST 函数【英文标题】:How to call POST function in Flutter 【发布时间】:2021-07-25 15:02:01 【问题描述】:

我正在使用HTTPClient 发出POST 请求并发布表单数据。当我尝试仅使用 3 个字段时请求成功,但现在我想添加所有字段,所以我在 parameter 和 POST 函数的 em>主体。

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

我在 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

【问题讨论】:

【参考方案1】:

我有这个帖子请求,您可以根据自己的需要更改它

这是发布功能

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

【讨论】:

以上是关于如何在 Flutter 中调用 POST 函数的主要内容,如果未能解决你的问题,请参考以下文章

如何在flutter中调用函数后刷新页面?

在 Flutter 中弹出屏幕后如何调用函数来更新值?

如何在 Flutter 小部件中测试回调函数

Flutter:如何在加载页面之前从 Api 获取数据 [关闭]

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

flutter mockito:如何调用存储库函数进行测试