The definition of this pattern:
- All inputs are streams.
- All outputs are streams.
- BLoC is a simple class that moves logic away from the interface.
Stream counter using the BLoC pattern:
import 'dart:async';
import 'package:flutter/material.dart';
class MyCounter extends StatelessWidget {
final CounterBloc counterBloc = CounterBloc();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Builder'),
),
body: Builder(
builder: (BuildContext context) {
return Container(
child: StreamBuilder<int>(
stream: counterBloc.getCount,
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.active) {
return Text(
'${snapshot.data.toString()}',
style: Theme.of(context).textTheme.display1,
);
} else if (snapshot.connectionState ==
ConnectionState.waiting) {
return Text(
'No data yet',
style: Theme.of(context).textTheme.display1,
);
} else if (snapshot.connectionState == ConnectionState.done) {
return Text('Done!');
} else if (snapshot.hasError) {
return Text('Error!');
} else {
return Text(snapshot.connectionState.toString());
}
}),
);
},
),
floatingActionButton: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: <Widget>[
FloatingActionButton(
onPressed: () => counterBloc.decreaseCounter,
child: Icon(Icons.exposure_neg_1),
backgroundColor: Theme.of(context).primaryColor,
mini: true,
),
FloatingActionButton(
onPressed: () => counterBloc.increaseCounter,
child: Icon(Icons.exposure_plus_1),
backgroundColor: Theme.of(context).primaryColor,
mini: true,
),
],
),
);
}
}
class CounterBloc {
final StreamController _controller = StreamController<int>();
int _counter = 1;
CounterBloc() {
Timer.periodic(Duration(seconds: 2), (timer) {
_controller.sink.add(_counter++);
});
}
Stream get getCount => _controller.stream;
get increaseCounter => _controller.sink.add(_counter++);
get decreaseCounter => _controller.sink.add(_counter--);
// void increaseCounter() {
// _controller.sink.add(_counter++);
// }
// void decreaseCounter() {
// _controller.sink.add(_counter--);
// }
void dispose() {
_controller.close();
}
}https://medium.com/@alexawaikin/bloc-pattern-for-flutter-on-the-classic-counter-example-d7af74df9a76
