-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstream_builder.dart
74 lines (63 loc) · 1.99 KB
/
stream_builder.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
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
import 'package:flutter/material.dart';
import 'dart:async';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'StreamBuilder Counter',
home: Scaffold(
appBar: AppBar(title: const Text('StreamBuilder Counter')),
body: const Center(child: CounterStreamBuilder()),
),
);
}
}
class CounterStreamBuilder extends StatefulWidget {
const CounterStreamBuilder({super.key});
@override
State<CounterStreamBuilder> createState() => _CounterStreamBuilderState();
}
class _CounterStreamBuilderState extends State<CounterStreamBuilder> {
int _counter = 0;
late StreamController<int> _counterStreamController;
@override
void initState() {
super.initState();
_counterStreamController = StreamController<int>.broadcast();
_startCounterStream();
}
// 创建一个每秒发出计数器更新的 Stream
void _startCounterStream() {
Timer.periodic(const Duration(seconds: 1), (timer) {
_counter++;
_counterStreamController.sink.add(_counter); // 向 Stream 发送新的计数器值
});
}
@override
Widget build(BuildContext context) {
print('StreamBuilder Widget rebuilt'); // 打印重建信息
return StreamBuilder<int>(
stream: _counterStreamController.stream, // 监听 Stream
initialData: _counter, // 可选的初始数据
builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
if (snapshot.hasData) {
return Text('Counter (StreamBuilder): ${snapshot.data}');
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return const CircularProgressIndicator();
}
},
);
}
@override
void dispose() {
print('CounterStreamBuilder Widget disposed'); // 打印 dispose 信息
_counterStreamController.close(); // 关闭 StreamController
super.dispose();
}
}