Flutter:Stream.periodic 示例

网友投稿 618 2022-05-30

本文将带您了解在 flutter中使用Stream.periodic的完整示例

该Stream.periodic构造,顾名思义,是用来创建流,在周期间隔反复广播事件。简单用法:

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

1

2

3

4

您可以在文档中找到有关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(); } }

1

2

3

4

5

6

7

8

9

10

11

12

13

Flutter:Stream.periodic 示例

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

结论

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

Flutter

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:软件总结--与回顾
下一篇:如何在 Linux 操作系统上编写和执行 XQuery 程序
相关文章