Flutter:Stream.periodic 示例
生活随笔
收集整理的這篇文章主要介紹了
Flutter:Stream.periodic 示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
本文將帶您了解在 Flutter中使用Stream.periodic的完整示例
該Stream.periodic構造,顧名思義,是用來創建流,在周期間隔反復廣播事件。簡單用法:
您可以在文檔中找到有關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 示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Flutter:使用 CustomCli
- 下一篇: 分享一个vscode主题收录网站,有了这