2021年2月10日星期三

Use of Streams/Sinks in a simple BLoC Example

I'm trying to understand a simple BLoC example for an app that increments/decrements a counter based on buttons (i.e., the default Flutter app, with an added button for decrementing counter).

I'm having trouble understanding why we need to manage three streams/sinks in class CounterBloc:

  1. StreamSink<int> get _inCounter => _counterStateController.sink;
  2. Stream<int> get counter => _counterStateController.stream;
  3. Sink<CounterEvent> get counterEventSink => _counterEventController.sink;

In particular, why do we need a separate variables for _inCounter and counter?

Full code below:

counter_event.dart:

  class IncrementEvent extends CounterEvent {}    class DecrementEvent extends CounterEvent {}  

counter_bloc.dart:

import 'package:flutter_bloc/counter_event.dart';    class CounterBloc {    int _counter = 0;      final _counterStateController = StreamController<int>();    StreamSink<int> get _inCounter => _counterStateController.sink;    Stream<int> get counter => _counterStateController.stream;      final _counterEventController = StreamController<CounterEvent>();    Sink<CounterEvent> get counterEventSink => _counterEventController.sink;      CounterBloc() {      _counterEventController.stream.listen(_mapEventToState);    }      _mapEventToState(CounterEvent event) {      if (event is IncrementEvent)        _counter++;      else        _counter--;        _inCounter.add(_counter);    }      void dispose() {      _counterStateController.close();      _counterEventController.close();    }  }  

Relevant excerpt of main.dart:

class _MyHomePageState extends State<MyHomePage> {    final _bloc = CounterBloc();      @override    Widget build(BuildContext context) {      return Scaffold(        appBar: AppBar(          title: Text(widget.title),        ),        body: Center(          child: StreamBuilder(            stream: _bloc.counter,            initialData: 0,            builder: (BuildContext context, AsyncSnapshot snapshot) {              return Column(                mainAxisAlignment: MainAxisAlignment.center,                children: <Widget>[                  Text(                    'You have pushed the button this many times:',                  ),                  Text(                    '${snapshot.data}',                    style: Theme.of(context).textTheme.headline4,                  ),                ],              );            },          ),        ),```  
https://stackoverflow.com/questions/66148408/use-of-streams-sinks-in-a-simple-bloc-example February 11, 2021 at 11:34AM

没有评论:

发表评论