Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete data from StreamBuilder after reading?

I want to delete data from my stream after I read it.
Basically I want the same system than channel in Go.

So, if I add 5, 3 and 2, my stream contains 5, 3 and 2.
When I start reading, I get 5, and my stream now contains 3 and 2 etc...

Is it possible?

EDIT: Here my problem with some code.
I use a StreamBuilder to receive data. When I change the state, it trigger again my function like if I'd just receive data.

child: StreamBuilder<Tag>(
  stream: widget.tagStream,
  initialData: Tag(),
  builder: (BuildContext context, AsyncSnapshot<Tag> snapshot) {
    /// This should be trigger only when I receive data
    if (mapController.ready && snapshot.hasData) {
      tag = snapshot.data;
      mapController.move(
        LatLng(tag.position.latitude, tag.position.longitude),
        mapController.zoom);
    }
    return RubberBottomSheet(...);
),

Here some context:
I have a map with icons representing objects. When I click on an icon or if I search the item related on my search bar, a RubberBottomSheet appears to show informations about the object. To do that, I use a StreamBuilder, so I just need to put the object clicked or searched in it to make my rubber appears and fill in. I also need to centrer on my icon to let the user know where is the object. My problem is that when I open or close my keyboard or when I use a setState (for changing the appearance of my search bar for example), it automatically trigger the StreamBuilder like if it receive new data.

Sorry, I should have started here...

like image 588
AmazingBite Avatar asked Jul 22 '19 10:07

AmazingBite


2 Answers

The answer of Amine seems to be the best, but I'd like to share my solution too, maybe it'll help some persons.

After I've executed my code, I pass an empty object to my Stream. I just have to verify that my object is not empty before executing my code and everything works like a charm.

builder: (BuildContext context, AsyncSnapshot<Tag> snapshot) {
  if (mapController.ready &&
      snapshot.hasData &&
      snapshot.data.mobile.nid != 0) {
    tag = snapshot.data;
    ... /// My code
    widget.tagStream.sink.add(Tag());
  }
like image 108
AmazingBite Avatar answered Oct 11 '22 07:10

AmazingBite


I've had similar behavior with a StreamBuilder and I couldn't find a solution for days. What I did instead is use a ListView builder that takes data from an InheritedWidget instead.

So basically instead of having to put data into the stream sink, I simply wrap my data setter in the InheritedWidget in a setState() and the ListView rebuilds every time I change the data.

N.B: My StreamBuilder also involved a map, I've always thought it was the one interfering with it but I never got to solve the problem. As in your case, every time I change the state, the stream rebuilds with the same data it had before.

like image 30
Amine Avatar answered Oct 11 '22 05:10

Amine