Flutter stream 添加小控件并显示

  • 时间:
  • 浏览:
  • 来源:互联网

代码:

import 'dart:async';

import 'package:flutter/material.dart';

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<StreamDemoHome> {
  //为了控制Stream 暂停。恢复。取消监听 新建
  StreamSubscription _streamSubscription;

  //控制器 可以去管理Stream
  StreamController<String> _streamDemo;

  //
  StreamSink _sinkDemo;

  String _data = "...";

  void onData(String data) {
    print("$data");
    setState(() {
      _data = data;
    });
  }

  void onDataTwo(String data) {
    print("onDataTwo:$data");
  }

  void onError(error) {
    print("onError $error");
  }

  void onDone() {
    print("onDone");
  }

  void _pauseStream() {
    print("Pause subscrition");
    _streamSubscription.pause();
  }

  void _addDataToStream() async {
    print("Add data to stream");
    String data = await fetchData();
    // _streamDemo.add(data);
    _sinkDemo.add(data);
  }

  void _resumeStream() {
    print("Resume subscrition");
    _streamSubscription.resume();
  }

  void _cancelStream() {
    print("Cancel subscrition");
    _streamSubscription.cancel();
  }

  Future<String> fetchData() async {
    await Future.delayed(Duration(seconds: 5));
    // throw "Something happend";
    return "hello~";
  }

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

    print("Create a stream.");
    _streamDemo = StreamController.broadcast();
    print("Start listening on a stream");
    _sinkDemo = _streamDemo.sink;
    _streamSubscription =
        _streamDemo.stream.listen(onData, onError: onError, onDone: onDone);

    _streamDemo.stream.listen(onDataTwo, onError: onError, onDone: onDone);

    print("Initialize completed'");
  }

  @override
  void dispose() {
    //小控件移除的时候关闭stream
    _streamDemo.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("$_data"),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                FlatButton(
                    onPressed: _addDataToStream, child: Text("Add Data")),
                FlatButton(onPressed: _pauseStream, child: Text("Pause")),
                FlatButton(onPressed: _resumeStream, child: Text("Resume")),
                FlatButton(onPressed: _cancelStream, child: Text("Cancel")),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

效果

本文链接http://www.dzjqx.cn/news/show-617108.html