flutter bloc_如何使用BLoC模式处理Flutter中的状态

本文介绍了如何在Flutter中使用BLoC模式处理应用程序状态。Flutter的状态管理可以通过Inherited Widget、Scoped Model和Redux等方式实现,但BLoC模式提供了一种更有效的方法。BLoC作为数据源(如API响应)和需要数据的小部件之间的中间件,使用响应式编程处理数据流。文章通过实例展示了如何将默认的Flutter示例应用转换为使用BLoC,包括创建CounterBLoC类和在StreamBuilder中展示数据。
摘要由CSDN通过智能技术生成

flutter bloc

Last year, I picked up Flutter and I must say it has been an awesome journey so far. Flutter is Google’s awesome framework for crafting high-quality applications for Android and iOS.

去年,我接了Flutter ,我必须说到目前为止,这是一段了不起的旅程。 Flutter是Google出色的框架,可为Android和iOS制作高质量的应用程序。

As with building almost any application, there’s always the need to handle application state. It is important that state management is handled efficiently, so as to avoid accruing technical debt, especially as your application grows and becomes more complex.

与构建几乎所有应用程序一样,始终需要处理应用程序状态。 重要的是要有效地处理状态管理,以避免产生技术负担,尤其是随着应用程序的增长和变得越来越复杂。

In Flutter, all UI components are widgets. As you start composing these widgets to create your awesome app, you’ll end up with a tree of deeply nested widgets. These widgets will most likely need to share application state with each other.

在Flutter中,所有UI组件都是小部件。 在开始组合这些小部件以创建出色的应用程序时,最终将得到一棵嵌套极深的小部件树。 这些小部件很可能需要彼此共享应用程序状态。

In this article, we’ll see how to handle state in Flutter using the BLoC pattern.

在本文中,我们将看到如何使用BLoC模式处理Flutter中的状态。

State management in Flutter can be achieved in a few different ways:

Flutter中的状态管理可以通过几种不同的方式来实现:

Inherited Widget: It allows you propagate data to its child widgets and the widgets are rebuilt whenever there is a change in the app’s state. The downside of using the InheritedWidget base class is that your state is final and this raises a problem if you want to mutate your state.

继承的窗口小部件 :它允许您将数据传播到其子窗口小部件,并且只要应用程序状态发生变化,就可以重新构建窗口小部件。 使用InheritedWidget基类的不利之处在于您的状态是最终状态,如果您要更改状态,则会产生问题。

Scoped Model: This is an external package built on top of InheritedWidget and it offers a slightly better way to access, update and mutate state. It allows you to easily pass a data Model from a parent Widget down to its descendants. In addition, it also rebuilds all of the children that use the model when the model is updated.

范围模型 :这是一个在InheritedWidget之上构建的外部软件包,它提供了一种更好的访问,更新和变异状态的方法。 它使您可以轻松地将数据模型从父Widget传递到其后代。 此外,更新模型时,它还会重建使用该模型的所有子代。

This might raise a performance issue, depending on how many ScopedModelDescendants a model has, as they’re rebuilt when there’s an update.

这可能会导致性能问题,具体取决于模型具有多少ScopedModelDescendant,因为在进行更新时会重新构建它们。

This issue can be fixed by decomposing the ScopedModel

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值