如何使用Dart的http传递自定义对象列表?

时间:2019-06-26 12:49:43

标签: http flutter dart

我正在尝试将自定义对象列表传递给我的API。

以下是我的代码

import 'package:meta/meta.dart';
import 'package:json_annotation/json_annotation.dart';

part 'submit_survey_question_options_model.g.dart';

@JsonSerializable(nullable: false)
class SubmitSurveyQuestionOptionsModel {
  String questionId;
  String answer;

  SubmitSurveyQuestionOptionsModel(
      {@required this.questionId, @required this.answer});

  factory SubmitSurveyQuestionOptionsModel.fromJson(
          Map<String, dynamic> json) =>
      _$SubmitSurveyQuestionOptionsModelFromJson(json);

  Map<String, dynamic> toJson() =>
      _$SubmitSurveyQuestionOptionsModelToJson(this);
}



Future<SubmitSurveyModel> submitSurvey(
      String userId,
      String facultyId,
      String surveyId,
      List<SubmitSurveyQuestionOptionsModel> submitSurveyQuestionOptionList,
      String subjectId) async {
    Map<String, dynamic> body = {
      "userId": userId,
      "facultyId": facultyId,
      "surveyId": surveyId,
      "survey": submitSurveyQuestionOptionList,
      "subjectId": subjectId
    };

    final response = await http.post(
      SUBMIT_SURVEY_URL,
      body: json.encode(body),
    );

    SubmitSurveyModel submitSurveyModel = standardSerializers.deserializeWith(
        SubmitSurveyModel.serializer, json.decode(response.body));


    return submitSurveyModel;
  }

我在json_serializable中使用pubspec。 我使用flutter packages pub run build_runner build

构建了可序列化的类

由于数据提交不正确,我无法解决问题?

我已经引用了以下链接,但无法正常工作

Flutter Error: type 'AddressInfo' is not a subtype of type 'String' in type cast

Dart Error Converting Object To JSON

3 个答案:

答案 0 :(得分:2)

尝试传递以下标题

  Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };

  final response = await http.post(Uri.encodeFull(url), body: json.encode(body), headers: headers);

答案 1 :(得分:0)

  1. 您需要在正文中添加 Dim delete as Range Set delete = ThisWorkbook.Worksheets("Someting").Range("A1:D4") delete.Clear 'It does clear my content delete.Delete 'Does the same fucntion as .Clear? I mean It doesn't delete all the formatting and width of the cells
  2. 添加这两个标头
    “内容类型”:“ application / json”,
      'Accept':'application / json',

    json.encode(body)

答案 2 :(得分:0)

你可以这样做:

List<String> comments = ["1", "2", "3"];
Map<String, dynamic> args = {"comments": comments};
String url = "test.com";
var body = json.encode(args);
final response = await http
    .post(url, body: body, headers: {'Content-type': 'application/json'});