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.
There are two types of streams in Flutter: single subscription streams and broadcast streams. Single subscription streams are the default.
Create Dynamic ListView using ListView. builder() And you would not know the number of elements in the list beforehand. In such scenarios, you can use ListView. builder() constructor of ListView class to create a dynamic list of widgets in ListView widget.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With