日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Flutter:Stream.periodic 示例

發布時間:2025/3/19 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Flutter:Stream.periodic 示例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

本文將帶您了解在 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);@overrideWidget build(BuildContext context) {return MaterialApp(// Hide the debug bannerdebugShowCheckedModeBanner: false,title: 'KindaCode.com',theme: ThemeData(primarySwatch: Colors.indigo,),home: const HomeScreen(),);} }class HomeScreen extends StatefulWidget {const HomeScreen({Key? key}) : super(key: key);@overrideState<HomeScreen> createState() => _HomeScreenState(); }class _HomeScreenState extends State<HomeScreen> {final Stream _myStream =Stream.periodic(const Duration(seconds: 1), (int count) {return count;});// The subscription on events from _myStreamlate StreamSubscription _sub;// This number will be displayed in the center of the screen// It changes over timeint _computationCount = 0;// Background color// In the beginning, it's indigo but it will be a random color laterColor _bgColor = Colors.indigo;@overridevoid 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();}@overrideWidget 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 listenerfloatingActionButton: FloatingActionButton(child: const Icon(Icons.stop,size: 30,),onPressed: () => _sub.cancel(),),);}// Cancel the stream listener on dispose@overridevoid dispose() {_sub.cancel();super.dispose();} }

結論

我們已經研究了在 Flutter中實現Stream.periodic的實際示例。如果您想了解更多關于流,類似的事情流,請繼續關注我!

總結

以上是生活随笔為你收集整理的Flutter:Stream.periodic 示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。