首页 > 解决方案 > 如何将 Future http 函数返回为布尔值,以便根据 http 响应的结果将其用于进一步的活动流

问题描述

这是一个编辑用户信息http post的代码,编辑成功与否都会返回响应消息。我希望这个函数能够返回一个布尔值,以便用户界面类能够知道该帖子是否成功。在以下代码中,它返回无法放入 if(bool) 函数的 Future。此 EditCustomerPost 类由用户界面类调用。

有没有办法将这个 http post 的结果返回给用户界面类(小部件类)?我想将结果返回为“布尔成功”。谢谢您的帮助!

import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:flutter/material.dart';
import './loginPost.dart';
import './loginPage.dart';
import './userInfoPage2.dart';

class EditCustomerPost {
  String jsonString;
  String reMsg;
  Map<String, dynamic> reMsgMap;
  bool success = false;
  BuildContext context;
  String token;
  String editWhat;

  EditCustomerPost({
    this.jsonString,
    this.reMsg,
    this.reMsgMap,
    this.context,
    this.token,
  });

  void showDialog1(String msg, bool success) {
    // flutter defined function
    String title = "Completed";
    if (!success) {
      title = 'Error';
    }
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text(title),
          content: new Text(msg),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void showDialog2() {
    // flutter defined function
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Access time expired"),
          content: new Text("Please Login again"),
          actions: <Widget>[
            // usually buttons at the bottom of the dialog
            new FlatButton(
              child: new Text("OK"),
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.push(
                  context,
                  MaterialPageRoute(builder: (context) => LoginPage()),
                );
              },
            ),
          ],
        );
      },
    );
  }

  // testcodepostrequest
  Future<bool> makePostEditRequest(String editWhat) async {
    // set up POST request arguments
    String url;
    if (editWhat == 'name') {
      url = 'http://firstcarestartup.appspot.com/customer/editName';
    } else if (editWhat == 'email') {
      url = 'http://firstcarestartup.appspot.com/customer/editEmail';
    } else if (editWhat == 'phoneNum') {
      url = 'http://firstcarestartup.appspot.com/customer/editPhoneNum';
    } else if (editWhat == 'profilePicture'){
      url = 'http://firstcarestartup.appspot.com/customer/editProfilePicture';
    }

    Map<String, String> headers = {
      "Content-type": "application/json",
      "Authorization": "Bearer " + token
    };
    print('==========HTTP POST FOR EDIT PROFILE==========\n');
    print('json post edit header= ' + headers.toString());
    print('json post edit request= ' + jsonString);
    print('json string length: '+jsonString.length.toString());
    print('url: '+url);
    // make POST request
    http.Response response =
        await http.post(url, headers: headers, body: jsonString);
    // check the status code for the result
    // int statusCode = response.statusCode;
    // this API passes back the id of the new item added to the body

    reMsgMap = jsonDecode(response.body);

    if (reMsgMap["error"] != null) {
      reMsg = reMsgMap["error"];
      success = false;
      if (reMsg == "jwt expired") {
        showDialog2();
      } else {
        print("error: " + reMsg);
      }
    } else if (reMsgMap["msg"] != null) {
      reMsg = reMsgMap["msg"];
      success = true;

      print(reMsgMap.toString());
    }
    if (success) {
      showDialog1(reMsg, success);
    }
    return success;
  }
}

标签: jsonhttpflutter

解决方案


您可以获取makePostEditRequest(...)解决其未来时返回的值。这是通过await内部async块完成的。有关用法示例,请查看代码变量中的其他地方在解析未来时如何从调用中response接收值。http.post(...)


推荐阅读