import 'package:flutter/material.dart'; import 'dart:async'; class StremaDemoSink extends StatelessWidget { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Strema案例'), ), body: StrameDemoHome(), ); } } class StrameDemoHome extends StatefulWidget { @override _StrameDemoHomeState createState() => _StrameDemoHomeState(); } class _StrameDemoHomeState extends State<StrameDemoHome> { StreamController<String> _strDemo; StreamSink _sinkDemo; @override void initState() { // TODO: implement initState super.initState(); _strDemo=StreamController.broadcast(); _sinkDemo=_strDemo.sink; _strDemo.stream.listen(onData,onDone: onDone,onError: onError); _strDemo.stream.listen(onDataTwo,onDone: onDoneTwo,onError: onErrorTwo); } @override void dispose() { // TODO: implement dispose //关掉不需要的Stream; _strDemo.close(); super.dispose(); } //监听数据 void onDataTwo(data){ print("two $data"); } //捕获错误 void onErrorTwo(error){ print("error is $error Two"); } //数据传递完成 void onDoneTwo(){ print("数据传递完成 Two"); } //监听数据 void onData(data){ print(data); } //捕获错误 void onError(error){ print("error is $error"); } //数据传递完成 void onDone(){ print("数据传递完成"); } Future<String> getData() async { await Future.delayed(Duration(seconds: 3)); return 'hello'; } //添加数据 void _addData() async { String data=await getData(); _sinkDemo.add(data); } @override Widget build(BuildContext context) { return Container( child: Row( children: <Widget>[ StreamBuilder( stream:_strDemo.stream , builder: (context,_snapshot){ return Text("${_snapshot.data}"); }, ), FlatButton( child: Text('添加数据'), onPressed: _addData, ), ], ), ); } }
关键代码:
Widget build(BuildContext context) { return Container( child: Row( children: <Widget>[ StreamBuilder( stream:_strDemo.stream , builder: (context,_snapshot){ return Text("${_snapshot.data}"); }, ), FlatButton( child: Text('添加数据'), onPressed: _addData, ), ], ), ); }
发表评论
侧栏公告
寄语
譬如朝露博客是一个分享前端知识的网站,联系方式11523518。
热评文章
标签列表
热门文章
友情链接