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

9,941

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.

Share:
9,941
Jayasurya
Author by

Jayasurya

Flutter amateur

Updated on December 11, 2022

Comments

  • Jayasurya
    Jayasurya over 1 year

    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.