Flutter GetX controller getting null instead of data

Issue

I have an API (which does work and returns a response, and I even can see the response 1 line above the return statement), but for some reason, when the data should be passed to the variable, I receive null, instead of the returned value.

the service DOES return data I DO get the value from the API, at least it shows that there is data in the variable before the return.

The resp variable, which should contain the data, shows that the value is empty.

api_service.dart <= Returns a value

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 <= Shows null, instead of the value.

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;
    }
  }
}

Solution

You’re missing a return before http.Response.fromStream(res).

Answered By – Tzach Ovadia

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.