Flutter Stream 简单的使用

一  简单使用

import 'dart:async';

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State createState() => _HomePageState();
}

class _HomePageState extends State {
  /// 1 创建
  StreamController> _dataController = StreamController();

  /// 2 获取streamSink 做 add 入口
  StreamSink get _dataSink => _dataController.sink;

  /// 3 获取Stream 用于监听
  Stream> get _dataStream => _dataController.stream;

  /// 4 事件订阅对象
  StreamSubscription? _dataSubScription;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 监听事件
    _dataSubScription = _dataStream.listen((event) {
      print(event);
    });
  }

  onClick() {
    // 改变事件
    _dataSink.add(["111"]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("data"),
        ),
        body: Column(
          children: [ElevatedButton(onPressed: onClick, child: Text("触发事件"))],
        ));
  }

  @override
  void dispose() {
    // TODO: implement dispose
    _dataSubScription!.cancel();
    _dataController.close();
    super.dispose();
  }
}

二 一个栗子

请求网络数据创建流

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State createState() => _HomePageState();
}

class _HomePageState extends State {
  static Dio _dio =
      Dio(BaseOptions(baseUrl: "https://interface.meiriyiwen.com"));

  static Future _getArtical() async {
    Response response =
        await _dio.get('/article/random', queryParameters: {"dev": 1});
    final data = response.data['data'];
    return data;
  }

  Stream? _futureStream;

  @override
  void initState() {
    // TODO: implement initState
    List> futures = [];
    for (var i = 0; i < 10; i++) {
      // 添加future
      futures.add(_getArtical());
    }
    // 生成Stream
    _futureStream = Stream.fromFutures(futures);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Random Artical"),
        ),
        body: SingleChildScrollView(
          child: Center(
            child: StreamBuilder(
              stream: _futureStream,
              builder: (context, AsyncSnapshot snapshot) {
                if (snapshot.hasData) {
                  Map article = snapshot.data;
                  return Container(
                    child: Column(
                      children: [
                        Text(article["title"]),
                        Text(article['content'])
                      ],
                    ),
                  );
                }
                return CircularProgressIndicator();
              },
            ),
          ),
        ));
  }

  @override
  void dispose() {
    // TODO: implement dispose

    super.dispose();
  }
}

Flutter Stream 简单的使用_第1张图片

 

你可能感兴趣的:(Flutter,相关,flutter)