Flutter StreamBuilder 实现局部刷新 Widget
import 'package:flutter/material.dart';
class CustomStreamBuilder extends StatefulWidget {
final Stream<int> stream;
final Widget child;
const CustomStreamBuilder({Key key, this.stream, this.child}) : super(key: key);
@override
_CustomStreamBuilderState createState() => _CustomStreamBuilderState();
}
class _CustomStreamBuilderState extends State<CustomStreamBuilder> {
StreamSubscription<int> _subscription;
int _count = 0;
@override
void initState() {
super.initState();
_subscription = widget.stream.listen((count) {
setState(() {
_count = count;
});
});
}
@override
void dispose() {
_subscription?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return widget.child;
}
}
这个代码示例展示了如何创建一个CustomStreamBuilder
类,它继承自StatefulWidget
。在initState
方法中,它订阅了传递给构造函数的流,并在流接收到数据时更新内部的_count
状态。如果小部件被销毁,dispose
方法将取消订阅,以防止内存泄漏。这个示例展示了如何使用Flutter中的Stream来实现局部刷新Widget的简单方法。
评论已关闭