Json 颤振中的HTTP POST请求

Json 颤振中的HTTP POST请求,json,flutter,http,dart,restapi,Json,Flutter,Http,Dart,Restapi,大家好,我希望大家都做得很好,我是第一个使用RestAPI构建flatter应用程序的新手,我必须使用RestAPI在flatter中添加一个联系人。问题是我没有找到正确的方法来做 我使用的是HTTP客户端,响应状态代码应该是201,当我在Main类中调用我的addContact()函数时,我成功地得到了这个响应,但当我在add\u contacts类中调用它时,我却没有得到这个响应 我还使用quicktype.io工具成功创建了模型,在UI部分,我有一个表单,现在我创建它的方式是,当我单击sa

大家好,我希望大家都做得很好,我是第一个使用RestAPI构建flatter应用程序的新手,我必须使用RestAPI在flatter中添加一个
联系人。问题是我没有找到正确的方法来做

我使用的是
HTTP客户端
,响应状态代码应该是
201
,当我在
Main类
中调用我的
addContact()
函数时,我成功地得到了这个响应,但当我在
add\u contacts类
中调用它时,我却没有得到这个响应

我还使用
quicktype.io
工具成功创建了模型,在UI部分,我有一个
表单
,现在我创建它的方式是,当我单击save时,它显示了一个带有
文本的
容器
,该容器保存了我的联系人,但由于我没有仅在该类中获得响应,因此我无法验证联系人是否保存

此外,我不知道如何实际
发布表单中的所有联系人详细信息,我已经添加了所有必要的
控制器
和所有内容,但我想在单击“保存”时发布所有联系人详细信息

根据我的
API文档
,我可以将任何联系人字段别名作为
参数
发布。例如,名字、姓氏、电子邮件等

我希望有人能指导我完成这项工作,我在下面附上的所有代码。 谢谢。

API\u管理器类:

Future<AddContactModel> addContact(
    String firstName,
    String lastName,
    String email,
  ) async {
    var client = http.Client();
    String addContactUrl =
        "https://example.com/ma/api/contacts/new";
    String basicAuth = 'Basic exampleauthkey';
    var response = await client.post(addContactUrl, headers: <String, String>{
      'authorization': basicAuth,
      "Accept": "application/json",
    }, body: {
      "firstname": firstName,
      "lastname": lastName,
      "email": email
    });
    print(response.statusCode);
    //developer.log(response.body);
    if (response.statusCode == 201) {
      final String responseString = response.body;
      return addContactModelFromJson(responseString);
    } else {
      return null;
    }
  }
class _AddContactsState extends State<AddContacts> {
  AddContactModel _contact;
  TextEditingController _ipCountryCode,
      _eventRevenue,
      _sendsSinceLastEngagement,
      _marketingEmailsOpened,
      _socialAwarenessClicks,
      _firstName,
      _lastName,
      _email,
      _reasonForEmailUnsubscribe;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String contactOwner,
      stage,
      leadStatus,
      tags,
      emailAddressQuarantined,
      selectCompany;
  DateTime timeFirstSeen,
      lastMarketingEmailClickDate,
      createDate,
      becameAnEvangelistDate;
  List contactOwnerItem = [
    "example owner 1",
    "example owner 2",
    "example owner 3",
    "example owner 4"
  ];
  List stageItem = [
    "Stage 1",
    "Stage 2",
    "Stage 3",
    "Stage 4",
  ];
  List leadStatusItem = [
    "Status 1",
    "Status 2",
    "Status 3",
    "Status 4",
  ];
  List tagsItem = [
    "tag1",
    "tag2",
    "tag3",
    "tag4",
  ];
  List emailAddressQuarantinedItem = ["On", "Off"];
  List selectCompanyItem = ["Company 1", "Other"];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _ipCountryCode = TextEditingController();
    _eventRevenue = TextEditingController();
    _sendsSinceLastEngagement = TextEditingController();
    _marketingEmailsOpened = TextEditingController();
    _socialAwarenessClicks = TextEditingController();
    _firstName = TextEditingController();
    _lastName = TextEditingController();
    _reasonForEmailUnsubscribe = TextEditingController();
    _email = TextEditingController();
  }

  Future saveContact() async{
    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);

    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: () {
                  // Validate returns true if the form is valid, or false otherwise.
                  if (_formKey.currentState.validate()) {
                    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 and was last active 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;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DateTimeFormField(
                          decoration: InputDecoration(
                              labelText: 'Became an evangelist date',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          onDateSelected: (DateTime value) {
                            setState(() {
                              becameAnEvangelistDate = value;
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _firstName,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'First Name',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _lastName,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Last Name',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    //validator: validateEmail,
                    onSaved: null,
                    controller: _email,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Email',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  TextFormField(
                    onSaved: null,
                    controller: _reasonForEmailUnsubscribe,
                    keyboardType: TextInputType.text,
                    decoration: InputDecoration(
                        labelText: 'Reason for email unsubscribe',
                        fillColor: Colors.white,
                        filled: true,
                        contentPadding: EdgeInsets.all(8)),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Tags',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: tags,
                          onChanged: (newValue) {
                            setState(() {
                              tags = newValue;
                            });
                          },
                          items: tagsItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Select a company',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: selectCompany,
                          onChanged: (newValue) {
                            setState(() {
                              selectCompany = newValue;
                            });
                          },
                          items: selectCompanyItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          isExpanded: true,
                          decoration: InputDecoration(
                              labelText: 'Contact Owner',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: contactOwner,
                          onChanged: (newValue) {
                            setState(() {
                              contactOwner = newValue;
                            });
                          },
                          items: contactOwnerItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: DropdownButtonFormField(
                          decoration: InputDecoration(
                              labelText: 'Stage',
                              fillColor: Colors.white,
                              filled: true,
                              contentPadding: EdgeInsets.all(8)),
                          value: stage,
                          onChanged: (newValue) {
                            setState(() {
                              stage = newValue;
                            });
                          },
                          items: stageItem.map((valueItem) {
                            return DropdownMenuItem(
                              value: valueItem,
                              child: Text(valueItem),
                            );
                          }).toList(),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
        ));
  }

Future

这里有很多问题,但是对于
async
代码,请尝试添加
wait

onPressed:()异步{
//如果表单有效,则Validate返回true,否则返回false。
if(_formKey.currentState.validate())异步{
等待saveContact();
}
},
要将所有表单数据发送到服务器,只需像在这里所做的那样,从定义的TextController添加更多字段

//在此处添加要发布到服务器的所有字段
final AddContactModel contact=等待API_Manager()。addContact(名字、姓氏、电子邮件等);

这里有很多问题,但是对于
async
代码,请尝试添加
wait

onPressed:()异步{
//如果表单有效,则Validate返回true,否则返回false。
if(_formKey.currentState.validate())异步{
等待saveContact();
}
},
要将所有表单数据发送到服务器,只需像在这里所做的那样,从定义的TextController添加更多字段

//在此处添加要发布到服务器的所有字段
final AddContactModel contact=等待API_Manager()。addContact(名字、姓氏、电子邮件等);

Hi,感谢您的回答,但是您能告诉我如何将整个JSON作为参数传递,而不是
firstName、lastName、email
。因为我有很多字段,无法将每个字段都作为参数传递给函数。您好,谢谢您的回答,但是您能告诉我如何将整个JSON作为参数传递,而不是
firstName、lastName、email
。因为我有很多字段,我不能将每个字段都作为参数传递给函数。