在屏幕上颤抖地显示来自服务器的JSON消息

时间:2019-09-14 22:38:52

标签: flutter dart httprequest

在我的flutter应用程序中,我正在调用一个函数,该函数将POST请求发送到我的服务器。我想发生的事情是,例如,如果忘记了一个字段,请从我的服务器显示该消息的JSON消息。

当前,此方法有效,但是JSON消息已打印在终端上,但是我希望消息显示在屏幕上。

dart文件:

import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'dart:async';
import 'dart:convert';

class Third extends StatelessWidget {
  makePostRequest() async {
    final uri = 'https://infinite-sea-61086.herokuapp.com/api/users/signup';
    final headers = {'Content-Type': 'application/json'};
    Map<String, dynamic> body = {'email': 'test550@gmail.com', 'password': 'test123456', 'confirmPassword': 'test123456'};
    String jsonBody = json.encode(body);
    final encoding = Encoding.getByName('utf-8');

    Response response = await post(
      uri,
      headers: headers,
      body: jsonBody,
      encoding: encoding,
    );

    int statusCode = response.statusCode;
    String responseBody = response.body;
    print(responseBody);
  }

  @override
  Widget build(BuildContext context) {
    makePostRequest();
    return new Center(
      child: new Container(
        child: Row(
          children: <Widget>[],
        ),
      ),
    );
  }
}

来自服务器的消息示例,该消息显示在终端上(我想在屏幕上显示):

Flutter:“用户名”为必填项

2 个答案:

答案 0 :(得分:0)

print()将在控制台上打印其参数。请将您的http响应放到Text小部件中。

此外,您可以将该文本小部件包装在FutureBuilder中,并将makePostRequest()作为将来的名称传递,以便在可用时显示响应。这个video可能会有所帮助。

答案 1 :(得分:0)

您必须使用FutureBuilder类在小部件之间发出请求。我刚刚更新了您的代码,它必须可以工作。

class Third extends StatelessWidget {
  Future<String> makePostRequest() async {
    final uri = 'https://infinite-sea-61086.herokuapp.com/api/users/signup';
    final headers = {'Content-Type': 'application/json'};
    Map<String, dynamic> body = {'email': 'test550@gmail.com', 'password': 'test123456', 'confirmPassword': 'test123456'};
    String jsonBody = json.encode(body);
    final encoding = Encoding.getByName('utf-8');

    Response response = await post(
      uri,
      headers: headers,
      body: jsonBody,
      encoding: encoding,
    );

    int statusCode = response.statusCode;
    String responseBody = response.body;
    print(responseBody);
    return responseBody;
  }

  @override
  Widget build(BuildContext context) {
    makePostRequest();
    return new Center(
      child: new Container(
        child: Row(
          children: <Widget>[
            FutureBuilder<String>(
              future: makePostRequest(),
              builder: (context, snapshot) {

                if(snapshot.hasData) {
                  return Text(snapshot.data);
                }

                return CircularProgressIndicator();
              },
            )
          ],
        ),
      ),
    );
  }
}