【问题标题】:http post request doesn't work for my flutter app codehttp post 请求不适用于我的颤振应用程序代码
【发布时间】:2021-09-07 17:08:16
【问题描述】:

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

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

enter image description here

附加邮递员代码中的请求正文。

这是邮递员中的响应正文: {enter image description here “处理时间”:1, “结果”: { "id": "fa6a14d5-2888-4634-8158-efcaa0690211", "noteType": "PRIVATE_NOTE", “隐私”:“私人”, “反应”:“中性”, “描述”:“KUSHAN 1”, “状态”:“活动”, “作者”:“测试用户”, "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),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      );
}

【问题讨论】:

  • 这个 API 在 postman 上工作?

标签: flutter dart mobile-application


【解决方案1】:

将您的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,其次,标头缺少两个参数。

【讨论】:

  • 首先感谢您的评论。它工作正常。我注意到你提到的错误。再次感谢。
  • 快乐的编码享受
【解决方案2】:

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

【讨论】:

  • 首先感谢您的回复。我添加了异步方法并尝试“等待 postData()。但仍然一样。我正在寻找一个完整的答案。代码中缺少一些东西。我找不到它
猜你喜欢
  • 2021-07-17
  • 1970-01-01
  • 1970-01-01
  • 2015-04-08
  • 2018-08-27
  • 2020-08-12
  • 1970-01-01
  • 2020-11-10
  • 2020-06-18
相关资源
最近更新 更多