【问题标题】:Flutter - Before .then is executed, Function is returning the value and after that reading .thenFlutter - 在执行 .then 之前,函数返回值,然后读取 .then
【发布时间】:2021-05-15 21:43:36
【问题描述】:

我在下面的代码中遇到了 2 个问题,我认为两者都是相关的。

  1. createFunction 显示错误 - “此函数的返回类型为 'FutureOr',但不以 return 语句结尾。尝试添加 return 语句,或将返回类型更改为 'void'。” - 我需要返回true或false,所以我必须使用返回类型bool。
  2. 当函数执行时,它运行平稳,直到问题区域(在代码中标记)。在这里它返回 null 然后返回执行 .then 。我需要在 http.post 执行后立即运行 .then 。在代码的末尾,它应该返回 true / false。

我们将不胜感激。

  Future<bool> createFunction(image) async {
    var request = new http.MultipartRequest("POST", Uri.parse(_urlImage));

    request.files.add(
        await http.MultipartFile.fromPath('imagefile', image));

    var response = await request.send().catchError((error) {
      throw error;
    });

    response.stream.transform(utf8.decoder).listen((value) async {
      return await http
          .post(
        _url,
        headers: {
          'content-type': 'application/json',
          'authorization': 'auth'
        },
        body: json.encode({data}),
      )

      ///// PROBLEM AREA //////

          .then((value) async {
        final _extractedData = await jsonDecode(value.body);
        if (value.statusCode == 201) {
          return true;
        } else {
          return false;
        }
      }).catchError((error) {
        throw error;
      });
    });
  }

【问题讨论】:

标签: flutter


【解决方案1】:

好的,对于此页面的下一个访问者,MultipartRequest 类的正确用法应该是 this

var uri = Uri.parse('https://example.com/create');
var request = http.MultipartRequest('POST', uri)
  ..fields['user'] = 'nweiz@google.com'
  ..files.add(await http.MultipartFile.fromPath(
      'package', 'build/package.tar.gz',
      contentType: MediaType('application', 'x-tar')));
var response = await request.send();
if (response.statusCode == 200) print('Uploaded!');

【讨论】:

    猜你喜欢
    • 2019-02-22
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-09
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    相关资源
    最近更新 更多