1

I am facing 2 problems with the below code and I think both are related.

  1. createFunction is showing an error - "This function has a return type of 'FutureOr< bool >', but doesn't end with a return statement. Try adding a return statement, or changing the return type to 'void'." - I need to return true or false, so I have to use return type bool.
  2. When the function is executed, it runs smoothly till the PROBLEM AREA (marked in the code). Here it returns null and then comes back to execute .then . I need to run .then right after http.post is executed. At the end of the code it should return true / false.

Any help will be highly appreciated.

  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;
      });
    });
  }
Ujjwal Raijada
  • 867
  • 10
  • 21
  • 1
    There are lots of issues in your code. You can retry with the following links: https://stackoverflow.com/a/49645074/10659482 and https://stackoverflow.com/a/51162343/10659482 – Akif Feb 12 '21 at 05:58
  • Thank you @Akif. It was really helpful. Can you write your answer in answer, so that I can mark it correct. This is for people who are facing similar problem. – Ujjwal Raijada Feb 12 '21 at 10:28

1 Answers1

2

Ok, for the next visitors to this page, the correct usage of MultipartRequest class should like 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!');
Akif
  • 7,098
  • 7
  • 27
  • 53