flutter之stream

class StreamDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('StreamDemo'), elevation: 0.0,),
      body: StreamDemoHome(),
    );
  }
}

class StreamDemoHome extends StatefulWidget {
  @override
  _StreamDemoHomeState createState() => _StreamDemoHomeState();
}

class _StreamDemoHomeState extends State {
  StreamSubscription _streamDemoSubscription;
  // StreamController可以控制、管理stream
  StreamController _streamDemo;
  StreamSink _sinkDemo;

  @override
  void dispose() {
    _streamDemo.close();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    print('Create a stream.');
    // 创建stream
//    Stream _streamDemo = Stream.fromFuture(fetchData());
    _streamDemo = StreamController();
    _sinkDemo = _streamDemo.sink;

    print('Start listening on a stream');
    // 使用stream上的数据需要监听这个stream,提供了几个事件的处理方法,比如有数据的时候,发生错误的时候,完成的时候
    // listen的返回值是StreamSubscription类型,使用它可以暂停、恢复、取消监听
//    _streamDemoSubscription = _streamDemo.listen(onData, onError: onError, onDone: onDone);
    // 使用streamController监听
    // 使用StreamBuilder时,这里就不需要监听了
//    _streamDemoSubscription = _streamDemo.stream.listen(onData, onError: onError, onDone: onDone);

    print('Initialize completed.');
  }

  void onData(String data) {
    print('$data');
  }

  void onError(error) {
    print('Error: $error');
  }

  void onDone() {
    print('Done');
  }

  void _pauseStream() {
    print('停止监听');
    _streamDemoSubscription.pause();
  }

  void _resumeStream() {
    print('恢复监听');
    _streamDemoSubscription.resume();
  }

  void _cancelStream() {
    print('取消监听');
    _streamDemoSubscription.cancel();
  }

  void _addDataToStream() async {
    print('给stream添加数据');

    String data = await fetchData();
//    _streamDemo.add(data);
    // 使用sink给stream添加数据
    _sinkDemo.add(data);
  }

  // 5秒后在stream上出现一个字符串
  Future fetchData() async {
    await Future.delayed(Duration(seconds: 5));
    return 'Hello World!';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 使用StreamBuilder可以根据stream上的数据去构建小部件,stream上的数据发生变化后会重新构建小部件
            StreamBuilder(
              stream: _streamDemo.stream,
              initialData: '...', // 设置初始值
              builder: (context, snapshot) {
                return Text('${snapshot.data}');
              },
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FlatButton(onPressed: _addDataToStream, child: Text('添加')),
                FlatButton(onPressed: _pauseStream, child: Text('停止')),
                FlatButton(onPressed: _resumeStream, child: Text('继续')),
                FlatButton(onPressed: _cancelStream, child: Text('取消')),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

你可能感兴趣的:(flutter之stream)