1
votes

I am trying to create a "CategoryStream" to update the UI based on the users choice.

This is my stream:

import 'dart:async';

class CategoryStream {
  StreamController<String> _categoryStreamController =
  StreamController<String>();

closeStream() {
  _categoryStreamController.close();
}

updateCategory(String category) {
  print("Update category in stream was called");
  print("the new category is: " + category);
  _categoryStreamController.sink.add(category);
}

Stream<String> get stream => _categoryStreamController.stream;
}

And my StreamBuilder looks like this:

 return StreamBuilder<String>(
  stream: CategoryStream().stream,
  builder: (context, snapshot) {
    return Container(
      color: Colors.white,
      child: Center(
        child: Text(snapshot.data.toString()),
      ),
    );
  },
);

So when the User choses a new category, i try to update the Stream like this:

  CategoryStream().updateCategory(currentChosenCategory);

Whatever i do, the result is always null. Although the right category is displayed in the print() function... What am i missing?

Maybe i need to work with a StreamProvider? Not a StreamBuilder? Because i am adding the data from a Parent-Widget to a Child-Widget of a Child-Widget..

1
add print(snapshot) before return Container( - what do you see on the logs?pskink
only null. The thing is, i'd like to provide more code, but the widgets are too large to post here. I think i might be working with the wrong instance of the stream? Because i created _categoryStream in both widgets. Wouldn't both instances work "with the same stream"?Arveni
you mean that snapshot is null? - it is impossiblepskink
yes, you are right, you cannot create multiple instances of CategoryStream with hope they will all refer to the same stream - thats why you have only "waiting" statepskink
hmmm, then i would refer to some good tutorials explaining Provider package ;-)pskink

1 Answers

1
votes

By default, the value of a StreamController is null. You need to set at initialData or add data to the stream before you call snapshot.data in your StreamBuilder:

 final CategoryStream _categoryStream = CategoryStream();
 return StreamBuilder<String>(
  stream: _categoryStream.stream,
  initialData: "",
  builder: (context, snapshot) {
    return Container(
      color: Colors.white,
      child: Center(
        child: Text(snapshot.data), //toString() is unnecessary, your data is already a string
      ),
    );
  },
);