【问题标题】:how can i make post method in flutter?我如何在颤振中制作发布方法?
【发布时间】:2019-12-12 08:23:24
【问题描述】:

如何在 Flutter 中为这样的 json 制作 post 方法

{
  "app_id": "3djdjkdjde",
  "include_external_user_ids": ["88"],
  "contents": {"en": "your order is created"}
}

当您在 json 中看到它的 json 我的内容问题时,它的值是 json

我用 post 方法制作了这个模型,但我不知道如何解析内容,你可以看到我现在将它的值设为 null

此时如果有静态消息的内容不需要动态值就可以了

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;

Notifications notificationsFromJson(String str) => Notifications.fromJson(json.decode(str));

String notificationsToJson(Notifications data) => json.encode(data.toJson());

class Notifications {
    String appId;
    List<String> includeExternalUserIds;
    Contents contents;

    Notifications({
        this.appId,
        this.includeExternalUserIds,
        this.contents,
    });

    factory Notifications.fromJson(Map<String, dynamic> json) => new Notifications(
        appId: json["app_id"],
        includeExternalUserIds: new List<String>.from(json["include_external_user_ids"].map((x) => x)),
        contents: Contents.fromJson(json["contents"]),
    );

    Map<String, dynamic> toJson() => {
        "app_id": appId,
        "include_external_user_ids": new List<dynamic>.from(includeExternalUserIds.map((x) => x)),
        "contents": contents.toJson(),
    };

        static Future<bool> postNotification(serviceUri, notificationData) async {

      var client = new http.Client();
      bool result = false;
      try { 
            final Map<String, String> _notificationData = {
              'app_id': notificationData['app_id'].toString(),
              'include_external_user_ids': orderData['include_external_user_ids'].toString(),
              "contents": null,

            };
            await client.post(serviceUri,
                        body: json.encode(_notificationData), 
                        headers: { 'Authorization' : 'Bearer ' + notificationData['Token'],  "Content-Type": "application/json"}
                      )
                      .then((http.Response response) {

                          var responseModel = json.decode(response.body);
                          if(responseModel != null && responseModel['status'] == true) {
                              result = true;
                          } else {
                              result = false;
                          }
                      });
      }
      catch(e) {
          result = false;
      }
      finally {
        client.close();
      }
      return result;
  }
}

class Contents {
    String en;

    Contents({
        this.en,
    });

    factory Contents.fromJson(Map<String, dynamic> json) => new Contents(
        en: json["en"],
    );

    Map<String, dynamic> toJson() => {
        "en": en,
    };
}

谢谢

【问题讨论】:

  • 你应该使用httpflutter包
  • 是的,我知道并且我构建了函数,但是我如何在 json 中为 json 发布帖子

标签: json http flutter


【解决方案1】:
Future<Map<String, dynamic>> postRequest(String url, Map jsonMap) async{
print('$url , $jsonMap');
HttpClient httpClient = new HttpClient();
HttpClientRequest request = await httpClient.postUrl(Uri.parse(url));
request.headers.set('content-type', 'application/json');
request.add(utf8.encode(json.encode(jsonMap)));
HttpClientResponse response = await request.close();
String reply = await response.transform(utf8.decoder).join();
print(reply);
httpClient.close();
Map<String, dynamic>map = json.decode(reply);
return map;

}

在你的 pubspec.yaml 文件中添加这个 http: ^0.12.0+1

【讨论】:

    猜你喜欢
    • 2021-09-29
    • 2020-04-22
    • 2020-10-13
    • 2020-06-26
    • 2018-08-09
    • 2019-12-19
    • 2021-02-10
    • 2021-08-18
    • 1970-01-01
    相关资源
    最近更新 更多