Search code examples
flutterdartstreamstream-builder

Why does StreamBuilder uses initialData multiple times and not it's latest snapshot?


I probably just misunderstand the dart's stream, but when I do this:

TabBarView(
  children: [
    ...
    StreamBuilder(
      builder(context, url){ 
        ...
        print(url);
        ...
      },
      stream: () async* { ... }().asBroadcastStream(),
      initialData: 'Dope',
    )
    ...
  ]
)

I get some strange behaviors when rendering the StreamBuilder using the TabBarView.

First, I have to use asBroadcastStream() otherwise I get a:

Bad state: Stream has already been listened to

which I acknowledge is a bad solution.

But, while the solution works, going back to the StreamBuilder in the TabBarView will now rebuild reusing initialData and not the stream's latest snapshot. Here's the output of print when going back to the tab twice:

I/flutter (14541): dope
I/flutter (14541): properURL
I/flutter (14541): dope
I/flutter (14541): dope

I image both issues are related, but I don't understand why StreamBuilder reuses the async* and initialData


Solution

  • Probably your widget is being recreated, transform it into a StatefulWidget and override dispose() with a print(disposed) inside of it to confirm.

    Also, inside the StreamBuilder print the snapshot.connectionState, your connectionState is probably changing to waiting to active and so the builder is being called with initalData.

    This is what I can guess for the little of code you posted, test this out and let me know how it goes.