Created
March 4, 2019 23:29
-
-
Save brianegan/240afc1439cd0b7d1b5900f537041088 to your computer and use it in GitHub Desktop.
Counter Bloc + Provider
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 'package:flutter/material.dart'; | |
import 'package:provider/provider.dart'; | |
import 'package:rxdart/rxdart.dart'; | |
class CounterBloc { | |
final _subject = BehaviorSubject<int>.seeded(0); | |
ValueObservable<int> get counter => _subject; | |
void increment() => _subject.value++; | |
void dispose() => _subject.close(); | |
} | |
void main() { | |
runApp( | |
StatefulProvider<CounterBloc>( | |
valueBuilder: (context) => CounterBloc(), | |
onDispose: (context, bloc) => bloc.dispose(), | |
child: MyApp(), | |
), | |
); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
title: 'Flutter Demo', | |
theme: ThemeData(primarySwatch: Colors.pink), | |
home: MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatelessWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
Widget build(BuildContext context) { | |
final bloc = Provider.of<CounterBloc>(context); | |
return Scaffold( | |
appBar: AppBar( | |
title: Text(title), | |
), | |
body: Center( | |
child: Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Text('You have pushed the button this many times:'), | |
StreamBuilder<Object>( | |
initialData: bloc.counter.value, | |
stream: bloc.counter, | |
builder: (context, snapshot) { | |
return Text( | |
'${snapshot.data}', | |
style: Theme.of(context).textTheme.display1, | |
); | |
}, | |
), | |
], | |
), | |
), | |
floatingActionButton: FloatingActionButton( | |
onPressed: bloc.increment, | |
tooltip: 'Increment', | |
child: Icon(Icons.add), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment