How to manage a stream of List of objects in Flutter?
Asked Answered
O

1

7

I've been dabbling with flutter for a few days, and I'm trying to make a simple ToDo app, as a learning project. I'm trying to implement something like a BLoC. A list of ListItem widgets is built with ListView.builder, wrapped in StreamBuilder. I have implemented a StreamController'<'List'<'Note'>'>', and whenever I add a new Note to the list, I've managed to add it to a temporary list and then pass the list through the StreamSink, though I suspect it rebuilds the whole ListView each time an item is added.

I'm trying to learn piece by piece, to understand streams in isolation. What is a better way of implementing this? I'm only able to find examples of simple types like Stream but not for complex types like Lists.

class Note {
  String title, note;
  Note(this.title, this.note);
}

class ListBloc {
  final notes = <Note>[];

  final _controller = StreamController<List<Note>>.broadcast();
  get controllerOut => _controller.stream.asBroadcastStream();
  get controllerIn => _controller.sink;

  addNewNote(Note note) {
    notes.add(note);
    controllerIn.add(notes);
  }

  void dispose() {
    _controller.close();
  }
}

I'm sure there's a better approach, that will add a new entry to the ListView. I've tried to not use any external packages since I just want to learn the basics.

Ofelia answered 13/5, 2019 at 10:58 Comment(1)
yes, it rebuilds the whole ListView each time an item is added. - there is nothing wrong with itOrton
T
7

For adding and removing items from the list, there's nothing wrong with rebuilding the whole list (That's how it's supposed to work).

But, for constantly updating items in the list, you can have a substream for each item to update only that item when it changes.

Tuxedo answered 13/5, 2019 at 11:17 Comment(1)
Do you have any example? how to update items in the list using stream controllerAlcinia

© 2022 - 2024 — McMap. All rights reserved.