Home > Blockchain >  Last Element is not getting stored in to an array in flutter?
Last Element is not getting stored in to an array in flutter?

Time:11-23

I am trying to store a response from the API to a list, the responses are getting stored but last element is not getting stored in the list.

var selectedImage = [];
    if (_image.length > 0) {
          for (var img in _image) {
            var request = http.MultipartRequest(
                'POST', Uri.parse('url'));
            request.fields.addAll({'userPath': "${widget.scanQr}"});
              var process = await http.MultipartFile.fromBytes(
                  'file', File(img.path).readAsBytesSync(),
                  filename: img.path.split("/").last,
                  contentType: MediaType('image', 'jpg'));
              request.files.add(process);
              var response = await request.send();
              print(response.statusCode);
              if (response.statusCode == 200) {
                response.stream.transform(utf8.decoder).listen((value) {
                  print("The value is $value");
                  selectedImage.add(value);
                  });
                print(selectedImage);
              }

The response I get when try to insert 2 images is:

[/uploads/jdsfei884ri4h449898/activity/file_1637650234094]

the first image is stored but the 2nd image didn't get stored.

CodePudding user response:

listen is not a syncronous method. You do not wait on it to finish, so when your piece of code is done, you have no idea if the stream listeners have already done their work. They might have added to the result array, or they might not have.

I suggest you use a method that ensures it did it's job before you move on.

It seems your stream only has one element anyway:

if (response.statusCode == 200) {
  const value = await stream.transform(utf8.decoder).first;
  selectedImage.add(value);
}

CodePudding user response:

Replace selectedImage.add(value); with selectedImage.addAll(value);

You are getting ArrayList from API, So basically add function add only object and addAll function add your whole list.

  • Related