import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';
void main()=>runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
StreamController<String> _streamController;
StreamSubscription _streamSubscription;
StreamSink _streamSink;
@override
void dispose() {
// TODO: implement dispose
_streamController.close();
super.dispose();
}
@override
void initState() {
// TODO: implement initState
_streamController=StreamController<String>.broadcast();
_streamSink=_streamController.sink;
_streamSubscription=_streamController.stream.listen(onData,onError: onError, onDone: onDone);
super.initState();
}
void addDataToStream()async{
print('begin to add data to stream');
String data=await(fetchData());
_streamSink.add(data);
print('Endding of data to stream');
}
pauseStream(){
_streamSubscription.pause();
}
cancelStrem(){
_streamSubscription.cancel();
}
resumeStream(){
_streamSubscription.resume();
}
onData(value){print('$value');}
onError(Error){print('$Error');}
onDone(){print('done');}
Future<String> fetchData()async{
int _index=0;
List<String> _listStream=['anounce','Bond','Country','Document','Effect','feel','Glove','Hover','Indent','Jack','Kick','Log','Moon','New','Opertiunity','Post','Queen'];
await Future.delayed(Duration(seconds:1));
_index=Random().nextInt(16);
return _listStream[_index];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Hello World'),),
body: Center(
child: Column(
children: <Widget>[
StreamBuilder(
stream: _streamController.stream,
initialData: '...',
builder:(BuildContext context,snapshot){
return Text('${snapshot.data}');
},
),
RaisedButton(
child: Icon(Icons.add),
onPressed:addDataToStream,
),
RaisedButton(
child: Text('Cancel'),
onPressed:cancelStrem,
),
RaisedButton(
child: Text('Pause'),
onPressed:pauseStream,
),
RaisedButton(
child: Text('Resume'),
onPressed:resumeStream,
),
],
),
),
);
}
}