Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initial value with StreamController without RxDart

Tags:

flutter

I'm using StreamControllers with Flutter. I have a model with some default values. From the widgets where I'm listening to the stream I want to supply some of those default values. I can see I can set an initial value on the StreamBuilder, but I want to use data from the model inside the bloc as initial data. So as soon as someone is using the snapshot data they get the default values. I've seen RxDart has a seed value, just wondering if this is possible without replacing with RxDart?

like image 724
Rasmus Christensen Avatar asked Oct 18 '25 21:10

Rasmus Christensen


2 Answers

What you are looking for is StreamController#add method,

Sends a data event.

Listeners receive this event in a later microtask.

Note that a synchronous controller (created by passing true to the sync parameter of the StreamController constructor) delivers events immediately. Since this behavior violates the contract mentioned here, synchronous controllers should only be used as described in the documentation to ensure that the delivered events always appear as if they were delivered in a separate microtask.

happy fluttering

like image 54
pskink Avatar answered Oct 20 '25 12:10

pskink


The default value for a stream can be specified when the class is initialized after adding a listener for that stream.

import 'dart:async';

enum CounterEvent { increase }

class CounterBloc {
  int value = 0;

  final _stateCntrl = StreamController<int>();
  final _eventCntrl = StreamController<CounterEvent>();

  Stream<int> get state => _stateCntrl.stream;
  Sink<CounterEvent> get event => _eventCntrl.sink;

  CounterBloc() {
    _eventCntrl.stream.listen((event) {
      _handleEvent(event);
    });
    _stateCntrl.add(value); // <--- add default value
  }

  void dispose() {
    _stateCntrl.close();
    _eventCntrl.close();
  }

  _handleEvent(CounterEvent event) async {
    if (event == CounterEvent.increase) {
      value++;
    }
    _stateCntrl.add(value);
  }
}
like image 35
Yauheni Prakapenka Avatar answered Oct 20 '25 10:10

Yauheni Prakapenka