Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage a stream of List of objects in Flutter?

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.

like image 533
Jayasurya Avatar asked May 13 '19 10:05

Jayasurya


People also ask

What are different types of streams in flutter?

There are two types of streams in Flutter: single subscription streams and broadcast streams. Single subscription streams are the default.

How do you create a dynamic list in flutter?

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.


Video Answer


1 Answers

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.

like image 158
Hassan Saleh Avatar answered Sep 19 '22 15:09

Hassan Saleh