Last active
January 4, 2019 18:11
-
-
Save 9jaswag/3e9f8b1d2d7f22e5d7b2b7720ae03058 to your computer and use it in GitHub Desktop.
Sample Flutter bloc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
// import 'package:rxdart/rxdart.dart'; if you want to make use of PublishSubject, ReplaySubject or BehaviourSubject. | |
// make sure you have rxdart: as a dependency in your pubspec.yaml file to use the above import | |
class CounterBloc { | |
final counterController = StreamController(); // create a StreamController or | |
// final counterController = PublishSubject() or any other rxdart option; | |
Stream get getCount => counterController.stream; // create a getter for our Stream | |
// the rxdart stream controllers returns an Observable instead of a Stream | |
void updateCount() { | |
counterController.sink.add(data); // add whatever data we want into the Sink | |
} | |
void dispose() { | |
counterController.close(); // close our StreamController to avoid memory leak | |
} | |
} | |
final bloc = CounterBloc(); // create an instance of the counter bloc | |
//======= end of CounterBloc file | |
//======= somewhere else in our app | |
import 'counter_bloc.dart'; // import the counter bloc file here | |
@override | |
void dispose() { | |
bloc.dispose(); // call the dispose method to close our StreamController | |
super.dispose(); | |
} | |
... | |
@override | |
Widget build(BuildContext context) { | |
return StreamBuilder( // Wrap our widget with a StreamBuilder | |
stream: bloc.getCount, // pass our Stream getter here | |
initialData: 0, // provide an initial data | |
builder: (context, snapshot) => Text('${snapshot.data}'), // access the data in our Stream here | |
); | |
} | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment