可指定一个stream对象,能够监听异步执行的状态,并在构造器中根据状态构建不同的界面。
相关组件
StreamBuilder基本使用
【stream】 : 子组件 【Stream
【initialData】 : 初始数据 【T】
【builder】 : 点击事件 【AsyncWidgetBuilder
import 'dart:async';
import 'package:flutter/material.dart';
class CustomStreamBuilder extends StatefulWidget {
@override
_CustomStreamBuilderState createState() => _CustomStreamBuilderState();
}
class _CustomStreamBuilderState extends State<CustomStreamBuilder> {
CountGenerator _generator = CountGenerator()..increment();
@override
void dispose() {
_generator.dispose(); //关闭控制器
super.dispose();
}
@override
Widget build(BuildContext context) {
return Container(
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
FlatButton(
color: Colors.blue,
shape: CircleBorder(
side: BorderSide(width: 2.0, color: Color(0xFFFFDFDFDF)),
),
child: Icon(
Icons.add,
color: Colors.white,
),
onPressed: () async {
await _generator.increment();
},
),
_buildStreamBuilder(),
FlatButton(
color: Colors.blue,
shape: CircleBorder(
side: BorderSide(width: 2.0, color: Color(0xFFFFDFDFDF)),
),
child: Icon(
Icons.remove,
color: Colors.white,
),
onPressed: () async {
await _generator.minus();
},
),
],
),
);
}
Widget _buildStreamBuilder() => StreamBuilder<int>(
stream: _generator.state,
builder: (BuildContext context, AsyncSnapshot snap) {
print(snap);
if (snap.connectionState == ConnectionState.done) {
return Text('Done');
}
if (snap.connectionState == ConnectionState.active) {
return Text(
snap.data.toString(),
style: Theme.of(context).textTheme.display1,
);
}
if (snap.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (snap.hasError) {
return Text('Error');
}
return Container();
});
}
class CountGenerator {
int _count = 0; //计数器数据
final StreamController<int> _controller = StreamController(); //控制器
Stream<int> get state => _controller.stream; //获取状态流
int get count => _count; //获取计数器数据
void dispose() {//关闭控制器
_controller.close();
}
Future<void> increment() async {//增加记数方法
_controller.add(++_count);
}
Future<void> minus() async {//增加记数方法
_controller.add(--_count);
}
}