Skip to content

Instantly share code, notes, and snippets.

@amrfarid140
Last active October 11, 2019 09:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amrfarid140/35aad73279cfcdc78613933aa5fb4591 to your computer and use it in GitHub Desktop.
Save amrfarid140/35aad73279cfcdc78613933aa5fb4591 to your computer and use it in GitHub Desktop.
Basic BLoC example
import 'package:flutter_web/material.dart';
import 'package:flutter_web_ui/ui.dart' as ui;
import 'dart:async';
void main() async {
await ui.webOnlyInitializePlatform();
runApp(MyApp());
}
abstract class MyHomePageAction {
MyHomePageAction();
factory MyHomePageAction.increment(int originalValue) => Increment(originalValue);
}
class Increment extends MyHomePageAction {
int originalValue;
Increment(this.originalValue) : super();
}
class MyHomePageBloc {
int _counter = 0;
final StreamController<int> _counterStream = StreamController.broadcast();
final StreamController<MyHomePageAction> _eventStream = StreamController();
Stream<int> get state => _counterStream.stream;
StreamSink<MyHomePageAction> get eventSink => _eventStream.sink;
MyHomePageBloc() {
_counterStream.add(_counter);
_eventStream.stream.listen((_) {
_onAddClicked();
});
}
void _onAddClicked() {
_counter++;
_counterStream.add(_counter);
}
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(
title: 'Flutter Demo Home Page',
bloc: MyHomePageBloc(),
),
);
}
}
class MyHomePage extends StatelessWidget {
final String title;
final MyHomePageBloc bloc;
MyHomePage({Key key, this.title, this.bloc}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(this.title),
),
body: Center(
child: StreamBuilder(
stream: bloc.state,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot<int> 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.display1,
),
],
);
},
),
),
floatingActionButton: StreamBuilder(
stream: bloc.state,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
return FloatingActionButton(
onPressed: () =>
bloc.eventSink.add(MyHomePageAction.increment(snapshot.data)),
tooltip: 'Increment',
child: Icon(Icons.add),
);
}),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment