Flutter GetX 控制器获取空值而不是数据

时间:2021-07-17 17:03:41

标签: flutter getx flutter-getx flutter-state flutter-get

我有一个 API(它可以工作并返回响应,我什至可以在 return 语句上方看到响应 1 行),但是出于某种原因,当数据应该传递给变量时,我收到空值,而不是返回值。

服务确实返回数据 我确实从API获取值,至少它表明返回前变量中有数据。

应该包含数据的 resp 变量显示该值为空。

api_service.dart <= 返回一个值

import 'dart:io';
import 'package:http/http.dart' as http;
import 'dart:convert';

class RemoteServices {
  static var client = http.Client();

  static Future sendImageForAnalysis(String filename) async {
    var request =
        http.MultipartRequest('POST', Uri.parse("http://10.0.2.2:8000/api"));

    request.files.add(http.MultipartFile('picture',
        File(filename).readAsBytes().asStream(), File(filename).lengthSync(),
        filename: filename.split("/").last));

    var res = await request.send();
    if (res.statusCode == 200) {
      http.Response.fromStream(res)
          .then((response) {
            var dataAsJson = json.decode(response.body);
            /* The variable from above does have data, it's not empty and none of the errors appears*/
            return dataAsJson;
          })
          .catchError((error) => print('Something went wrong')) /* Error is not showing */
          .whenComplete(() => print('Got data from the server'));
    } else {
      /* Code does not get here */
      return {'name': 'x'};
    }
  }
}

controller_results.dart <= 显示空值,而不是值。

import 'package:face_search/services/api_service.dart';
import 'package:get/get.dart';

class ResultsController extends GetxController {
  final data = {}.obs;
  final name = ''.obs;

  void getItemData(imagePath) async {
    var resp = await RemoteServices.sendImageForAnalysis(imagePath);
    print(resp); /* This is empty for some reason */
    if (resp != null) {
      data.value = resp;
    }
  }
}

2 个答案:

答案 0 :(得分:1)

您在 return 之前缺少一个 http.Response.fromStream(res)

答案 1 :(得分:0)

api的结果是否返回json?如果它返回 json,为什么不尝试为它创建模型并调用控制器上的列表,以便您可以自由地知道它是否有数据要返回。