Last active
September 25, 2017 05:24
-
-
Save gavindoughtie/147773884b38e3ce7e20d25879a51f23 to your computer and use it in GitHub Desktop.
looking for stream replay
This file contains 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 'dart:async'; | |
void main() { | |
runApp(new MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
// This widget is the root of your application. | |
@override | |
Widget build(BuildContext context) { | |
return new MaterialApp( | |
title: 'Flutter Demo', | |
theme: new ThemeData( | |
primarySwatch: Colors.blue, | |
), | |
home: new MyHomePage(title: 'Flutter Demo Home Page'), | |
); | |
} | |
} | |
class MyHomePage extends StatefulWidget { | |
MyHomePage({Key key, this.title}) : super(key: key); | |
final String title; | |
@override | |
_MyHomePageState createState() => new _MyHomePageState(); | |
} | |
typedef S ReduceFn<S, T>(S stream, T input); | |
StreamTransformer makeReduceTransformer(reduceFn, seed) { | |
var state = seed; | |
return new StreamTransformer.fromHandlers(handleData: (s, sink) { | |
state = reduceFn(state, s); | |
sink.add(state); | |
}); | |
} | |
class _MyHomePageState extends State<MyHomePage> { | |
StreamController<int> _clickStream = new StreamController<int>.broadcast(sync: true); | |
Stream<int> _stateStream; | |
Stream<String> _fizzBuzzStream; | |
@override | |
void initState() { | |
super.initState(); | |
int stateFunc(int previous, int input) { | |
return previous + input; | |
} | |
_stateStream = _clickStream.stream.transform(makeReduceTransformer(stateFunc, 0)); | |
_fizzBuzzStream = _stateStream.map((int val) { | |
if (val % 5 == 0) { | |
return 'fizz'; | |
} | |
if (val % 10 == 0) { | |
return 'buzz'; | |
} | |
return '--'; | |
}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return new Scaffold( | |
body: new Center( | |
child: new Column( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
new Text( | |
'You have pushed the button this many times:', | |
), | |
new StreamBuilder( | |
stream: _stateStream, | |
builder: (context, snapshot) => new Text( | |
'${snapshot.data ?? 0}', | |
style: Theme.of(context).textTheme.display1, | |
), | |
), | |
new StreamBuilder( | |
stream: _fizzBuzzStream, | |
builder: (context, snapshot) => new Text( | |
snapshot.data ?? '--', | |
style: Theme.of(context).textTheme.display2, | |
), | |
), | |
], | |
), | |
), | |
floatingActionButton: new FloatingActionButton( | |
onPressed: () => _clickStream.add(1), | |
tooltip: 'Increment', | |
child: new Icon(Icons.add), | |
) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment