在使用 Bloc 的过程中,虽然可以实现状态管理,但是没有直接获取状态的方式。因此,如果想要在 UI 层面直接获取状态,我们需要借助 StreamBuilder。
示例代码:
class MyHomePage extends StatelessWidget {
final counterBloc = CounterBloc();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Bloc State Management"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'You have pushed the button this many times:',
),
StreamBuilder(
stream: counterBloc.counterStream,
initialData: 0,
builder: (BuildContext context, AsyncSnapshot snapshot) {
return Text(
'${snapshot.data}',
style: Theme.of(context).textTheme.headline4,
);
},
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => counterBloc.incrementCounter(),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
在上面的代码中,我们使用 StreamBuilder 来监听计数器值的变化,并根据变化来更新 UI 界面上的值。这样就可以直接获取到状态啦!