Blocdoesn'tprovidethestateflutter。
创始人
2024-12-22 20:00:11
0

在使用 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 界面上的值。这样就可以直接获取到状态啦!

相关内容

热门资讯

第6分钟了解(德州ai)外挂智... 第6分钟了解(德州ai)外挂智能ai辅助代打(透视)攻略教程(2023已更新)(哔哩哔哩);相信小伙...
第2分钟了解(tritonpo... 第2分钟了解(tritonpoker)外挂辅助插件安装代打(透视)黑科技教程(2024已更新)(哔哩...
第9分钟了解(WPK技巧)黑科... 第9分钟了解(WPK技巧)黑科技透明挂辅助软件(透视)教你攻略(2024已更新)(哔哩哔哩)是一款可...
七分钟了解(aapoker德州... 七分钟了解(aapoker德州俱乐部)软件透明挂辅助科技(透视)线上教程(2022已更新)(哔哩哔哩...
1分钟了解(Wepoke开发)... 1分钟了解(Wepoke开发)黑科技透明挂辅助黑科技(透视)扑克教程(2021已更新)(哔哩哔哩);...
第六分钟了解(wpk德州ai机... 第六分钟了解(wpk德州ai机器人)外挂辅助插件安装科技(透视)规律教程(2024已更新)(哔哩哔哩...
第1分钟了解(Wepoke技术... 第1分钟了解(Wepoke技术)外挂透明挂辅助下载(透视)实用技巧(2023已更新)(哔哩哔哩);1...
第十分钟了解(新版Wepoke... 第十分钟了解(新版Wepoke)软件透明挂辅助app(透视)曝光教程(2020已更新)(哔哩哔哩);...
第3分钟了解(wepOke)外... 第3分钟了解(wepOke)外挂辅助插件安装app(透视)第三方教程(2021已更新)(哔哩哔哩),...
八分钟了解(德扑之星设置)外挂... 八分钟了解(德扑之星设置)外挂辅助插件安装黑科技(透视)AI教程(2021已更新)(哔哩哔哩);人气...