您当前的位置: 首页 >  flutter

大前端之旅

暂无认证

  • 3浏览

    0关注

    403博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

Flutter:Stream.periodic 示例

大前端之旅 发布时间:2021-10-14 08:04:24 ,浏览量:3

本文将带您了解在 Flutter中使用Stream.periodic的完整示例 该Stream.periodic构造,顾名思义,是用来创建流,在周期间隔反复广播事件。简单用法:

final Stream _myStream =
    Stream.periodic(const Duration(seconds: 1), (int count) {
       // Do something and return something here
});

您可以在文档中找到有关Stream.periodic 的更多信息。但是,如果您觉得单词太无聊和令人困惑,并且只想深入研究代码,请继续阅读下面的示例。

我们将要构建的应用程序的背景颜色会随着时间而变化。它还在屏幕中央显示递增的数字。我们可以通过按下浮动按钮来阻止这些无情的行为。

这是它的工作原理:

main.dart 中的完整源代码和解释:

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:math';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // Hide the debug banner
      debugShowCheckedModeBanner: false,
      title: 'KindaCode.com',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

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

class _HomeScreenState extends State {
  final Stream _myStream =
      Stream.periodic(const Duration(seconds: 1), (int count) {
    return count;
  });

  // The subscription on events from _myStream
  late StreamSubscription _sub;

  // This number will be displayed in the center of the screen
  // It changes over time
  int _computationCount = 0;

  // Background color
  // In the beginning, it's indigo but it will be a random color later
  Color _bgColor = Colors.indigo;

  @override
  void initState() {
    _sub = _myStream.listen((event) {
      setState(() {
        _computationCount = event;

        // Set the background color to a random color
        _bgColor = Colors.primaries[Random().nextInt(Colors.primaries.length)];
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: _bgColor,
      appBar: AppBar(
        title: const Text('Lucklyの博客'),
        backgroundColor: Colors.transparent,
      ),
      body: Center(
        child: Text(
          _computationCount.toString(),
          style: const TextStyle(fontSize: 150, color: Colors.white),
        ),
      ),
      // This button is used to unsubscribe the stream listener
      floatingActionButton: FloatingActionButton(
        child: const Icon(
          Icons.stop,
          size: 30,
        ),
        onPressed: () => _sub.cancel(),
      ),
    );
  }

  // Cancel the stream listener on dispose
  @override
  void dispose() {
    _sub.cancel();
    super.dispose();
  }
}
结论

我们已经研究了在 Flutter中实现Stream.periodic的实际示例。如果您想了解更多关于流,类似的事情流,请继续关注我!

关注
打赏
1660524863
查看更多评论
立即登录/注册

微信扫码登录

0.0381s