7

I have a Bloc class that needs three streams based on the same stream controller.

class TodoBloc {

  final _todoController = StreamController<List<TodoModel>>();

  get allTodoStream => _todoController.stream;

  get activeTodoStream => _todoController.stream
          .map<List<TodoModel>>(
              (list) => list.where((item) => item.state == 0));

  get completedTodoStream => _todoController.stream
          .map<List<TodoModel>>(
              (list) => list.where((item) => item.state == 1));}

it's a list of to-dos which have states. I'd like to retrieve the to-dos with an active state in a stream separate from the one that retrieves the other states.

I have a method that's responsible for the filtering and returns a stream depending on the filter value. here's the method:

Stream<List<TodoModel>> filterTodoLs(String filter) {
    if (filter == 'all') {
      return todoStream;
    } else if (filter == 'completed') {
      return completedStream;
    } else if (filter == 'active') {
      return activeStream;
    }
    return todoStream;
}

later to be used in a widget like the following:

 return StreamBuilder<List<TodoModel>>(
      stream: bloc.filterTodoLs(filter),
      builder:(BuildContext context, AsyncSnapshot<List<TodoModel>> todoSnapShot) {}

the snapshot is empty so far. how can i filter my original stream and return different ones depending on the filter applied to that stream?

M Reza
  • 18,350
  • 14
  • 66
  • 71
Salma
  • 1,211
  • 2
  • 16
  • 33

1 Answers1

8

A StreamController.broadcast() creates a stream that can have multiple listeners.

See https://www.dartlang.org/tutorials/language/streams#broadcast-streams

The details of switching between the different filtered streams depends on context not provided in the question.

Nate Bosch
  • 10,145
  • 2
  • 26
  • 22
  • What if I have a widget wrapped in a streambuilder attached to a stream and say I am using the same widget at multiple places but change of a single widget updates to all the widgets because they all are listening to the same stream how to make the same widget listen to different streams – Mahesh Jamdade Jan 11 '20 at 07:24
  • I have got it a single instance of that class has to be created to create a unique stream – Mahesh Jamdade Jan 11 '20 at 08:06