Ujjwal Raijada
Ujjwal Raijada

Reputation: 975

Flutter - Before .then is executed, Function is returning the value and after that reading .then

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

Upvotes: 1

Views: 737

Answers (1)

Akif
Akif

Reputation: 7640

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'] = '[email protected]'
  ..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!');

Upvotes: 2

Related Questions