2

What is actually happening?

main.dart

In initState, we are calling server to get image from database, then add it into sink

var capturedImagesList = List<dynamic>();

    @override
      void initState() {
        super.initState();  
         _bloc.getImages(); // 
        });
      }

bloc class

  final _urlImage = BehaviorSubject<List<dynamic>>();
  get urlImageSink => _urlImage.sink;
  get urlImageStream => _urlImage.stream;

 Future getImages() async {
    Response image = await _repo.getImages();  // call server
    var imageResponse = Response.fromJson(image.body);
    urlImageSink.add(imageResponse.images);  // add image to sink
  }

The retrieved image will be displayed in horizontal ListView.

enter image description here

When the + image is clicked, it will allow user to select an image from gallery, then placed beside the ListView as image below.

enter image description here

Everything works fine !

But when I click the + image again to add one more image, it throw us this error

[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Concurrent modification during iteration: Instance(length:3) of '_GrowableList'. E/flutter (32313): #0 List.addAll (dart:core-patch/growable_array.dart:187:11)

main.dart

This is the code after image is selected from gallery.

 @override
  List<dynamic> userImage(File images) {
    if (images != null) {
      capturedImagesList.add(images.path);  // add selected image to List
      capturedImagesList.addAll(_bloc.urlImageStream.value);  // add the server image to list
       _bloc.urlImageSink.add(capturedImagesList);  // add all images to list
    }
    return null;
  }

Errror is pointed to this line

capturedImagesList.addAll(_bloc.urlImageStream.value);

Why it works for the first time, but failed for second time?

John Joe
  • 12,412
  • 16
  • 70
  • 135

3 Answers3

1

Did you check out this thread: Exception: Concurrent modification during iteration: Instance(length:17) of '_GrowableList'

I quote from the article:

This error means that you are adding or removing objects from a collection during iteration. This is not allowed since adding or removing items will change the collection size and mess up subsequent iteration.

So I don't see all the code, but could it be that when you add a picture via the add button, you clear the list or remove the current items?

Jente Vets
  • 31
  • 3
1

You could just do that

_bloc.urlImageSink.add([images])

And the image would reflected immediately in UI.

I think the problem is in this line

capturedImagesList.addAll(_bloc.urlImageStream.value);

this looks strange, you can't copy the stream into array, it won't work.

LITSLINK
  • 36
  • 3
0

Try to clear the array like this before doing addAll

  _myLeaveRequests?.clear();
SwiftiSwift
  • 7,528
  • 9
  • 56
  • 96