http post 请求不适用于我的 flutter 应用程序代码

http post request doesn't work for my flutter app code

我正在尝试向 post 人员 URL 发出 HTTP post 请求。在代码中,我找不到任何错误,但它在 flutter 应用程序中不起作用。

虽然在文本框中输入了数据,但响应并没有在颤动中显示。我附上了图片

enter image description here

post附上人工代码的请求正文。

这是postman中的响应体: {enter image description here “处理时间”:1, “结果”: { “id”:“fa6a14d5-2888-4634-8158-efcaa0690211”, "noteType": "PRIVATE_NOTE", “隐私”:“私人”, “反应”:“中性”, “描述”:“贵霜一号”, “状态”:“活跃”, "author": "测试用户", "authorId": "00000000-0000-0000-0000-000000000000", “修改”:“2021-09-07T13:59:33.9926797Z”, “标记”:假 } }

这是我的代码:

import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

postData() async {
  try {
    var response = await http.post(
        Uri.parse("https://zen-api-1010.azure-api.net/notes/v1/create"),
        headers: {
          "Ocp-Apim-Subscription-Key": "008c47b597e54aedadbd5e4d270b35ed",
          "Ocp-Apim-Trace": "true"
        },
        body: {
          "noteType": 0.toString(),
          "description": "KUSHAN  1".toString(),
          "authorReaction": 0.toString(),
          "privacy": 0.toString(),
        });
    print(response.body);
  } catch (e) {
    print(e);
  }
}

class NavPrivatePage extends StatefulWidget {
  @override
  _NavPrivatePageState createState() => _NavPrivatePageState();
}

class _NavPrivatePageState extends State<NavPrivatePage> {
  TextEditingController noteTypeController = TextEditingController();
  TextEditingController descriptionController = TextEditingController();
  TextEditingController authorReactionController = TextEditingController();
  TextEditingController privacyController = TextEditingController();

  bool inVisible = true;
  bool isNotVisible = false;

  @override
  Widget build(BuildContext context) => Scaffold(
        appBar: AppBar(
          title: Text(
            'Private Note Auto Expand',
            style: TextStyle(
              fontSize: 14,
            ),
          ),
          centerTitle: true,
          backgroundColor: const Color.fromRGBO(255, 191, 0, 1),
        ),
        body: SingleChildScrollView(
          child: Center(
            child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Visibility(
                    visible: inVisible,
                    child: TextButton(
                      onPressed: () {
                        setState(() {
                          isNotVisible = !isNotVisible;
                        });
                      },
                      child: Text(
                        'Create Private Note',
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.grey[900],
                      ),
                    ),
                  ),
                  Visibility(
                    visible: isNotVisible,
                    child: Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: TextFormField(
                        controller: descriptionController,
                        autofocus: false,
                        onChanged: (text) {
                          print("Text $text");
                        },
                        minLines: 2,
                        maxLines: 20,
                        keyboardType: TextInputType.multiline,
                        decoration: InputDecoration(
                          hintText: 'Enter your message here',
                          hintStyle: TextStyle(
                            color: Colors.grey[600],
                            fontSize: 12,
                          ),
                          border: OutlineInputBorder(
                            borderRadius: BorderRadius.all(Radius.circular(5)),
                          ),
                        ),
                      ),
                    ),
                  ),
                  Visibility(
                    visible: isNotVisible,
                    child: TextButton(
                      onPressed: () {
                        postData();
                      },
                      child: Text(
                        'Submit',
                        style: TextStyle(
                          color: Colors.white,
                        ),
                      ),
                      style: TextButton.styleFrom(
                        backgroundColor: Colors.grey[600],
                      ),
                    ),
                  ),
                  Visibility(
                    visible: isNotVisible,
                    child: Center(
                      child: Card(
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10)),
                        color: Colors.grey[300],
                        child: Container(
                          padding: EdgeInsets.all(10),
                          height: 130,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              ListTile(
                                trailing: Icon(Icons.more_horiz),
                                leading: CircleAvatar(
                                  backgroundImage: NetworkImage(
                                      'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500'),
                                ),
                                subtitle: Text(
                                  '2 days ago',
                                  style: TextStyle(
                                    color: Colors.grey[800],
                                  ),
                                ),
                              ),
                              Text(
                                  'This is a private note that auto expands based on the text entered. The background will determine the privacy level of the post',
                                  style: TextStyle(
                                    fontSize: 10,
                                    color: Colors.black87,
                                  ),
                                  textAlign: TextAlign.justify),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
}

我建议将您的 TextButtononPressed 设为 async 方法并在其中尝试 await postData()

将您的 postData() 更改为

postData() async {
    try {
      var response = await http.post(
          Uri.parse("https://zen-api-1010.azure-api.net/notes/v1/create"),
          headers: {
            "Content-type": "application/json",
            "Accept": "application/json",
            "Ocp-Apim-Subscription-Key": "008c47b597e54aedadbd5e4d270b35ed",
            "Ocp-Apim-Trace": "true"
          },
          body: jsonEncode({
            "noteType": 0.toString(),
            "description": "KUSHAN  1".toString(),
            "authorReaction": 0.toString(),
            "privacy": 0.toString(),
          }));
      print(response.statusCode);
    } catch (e) {
      print(e);
    }
  }

问题是 api 接受 json 数据,但您发送的地图需要首先编码到 json,其次 header 有两个缺少参数。