Flutter2.0 StreamSink 代替_streamDemo加载数据

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

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

  //
  StreamSink _sinkDemo;

  void onData(String data) {
    print("$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 fetchData() async {
    await Future.delayed(Duration(seconds: 5));
    // throw "Something happend";
    return "hello~";
  }

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

    print("Create a stream.");
    _streamDemo = StreamController();
    print("Start listening on a stream");
    _sinkDemo = _streamDemo.sink;
    _streamSubscription =
        _streamDemo.stream.listen(onData, 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: 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")),
          ],
        ),
      ),
    );
  }
}

效果和之前一样

Flutter2.0 StreamSink 代替_streamDemo加载数据_第1张图片

你可能感兴趣的:(042Flutter)