flutter中使用BloC模式

业务逻辑组件

什么是BloC模式?

BloC【Business Logic Component】模式是paolo soares 和 cong hui 在2018年Google dartconf上提出的,具体的视频你可以参考YouTube.

从视频中可以看到paolo soares用一个及其简单的例子阐述了传统写法的问题:

1、业务逻辑和UI组件糅合在一起。

2、不方便测试,不利于单独的测试业务逻辑部分。

3、不能更好的重用业务逻辑代码,体现在,如果网络请求的逻辑有所变动的话,加入这个业务功能被两个端(web、flutter)使用的话,是需要改动两个地方的。

基于上面出现的一些问题,paolo soares顺利的将我们重传统的开放方式,引入到了Bloc模式。

传统的开发方式

传统的开发方式,可以很明显的看出来,其中网络请求的代码和ui界面写了一起,日积月累,这里面的代码复杂度会随之增加,下面是改造之后的编写方式,将业务逻辑抽出来,放到了一个businessLogic中了。

改造之后的方式

可以看到改造之后,变得清晰多了,这个文件几乎就全部是UI构建的代码,所有的逻辑都抽到了businessLogic中了。做过android开发的小伙伴看到这个模式就一定会联想到MVP设计模式了吧,其中Presenter似乎就是干businessLogic的事情了。更具我自己的一点理解来看,实际上BloC设计模式,似乎和MVP没有什么本质区别,两种设计模式的最终目的就是为了把和UI糅合在一起的业务逻辑代码剥离开来,单独的抽取到一层中。

如何用BloC模式

应用

上图是描述的是,组件的一些基本行为,【展示数据】,【发送事件】。在flutter中,实现BloC模式的精髓就是,

展示的数据从BloC中来,具体到了stream上,有了stream的到来,就可以使用StreamBuilder来构建ui了。

// TODO(ianh): remove unreachable code above once https://github.com/dart-lang/linter/issues/1141 is fixed
class StreamBuilder<T> extends StreamBuilderBase<T, AsyncSnapshot<T>> {
  /// Creates a new [StreamBuilder] that builds itself based on the latest
  /// snapshot of interaction with the specified [stream] and whose build
  /// strategy is given by [builder]. The [initialData] is used to create the
  /// initial snapshot. It is null by default.
  const StreamBuilder({
    Key key,
    this.initialData,
    Stream<T> stream,
    @required this.builder
  })
      : assert(builder != null),
        super(key: key, stream: stream);

发送事件丢给BloC处理,具体到了sink上。

/**
 * A generic destination for data.
 *
 * Multiple data values can be put into a sink, and when no more data is
 * available, the sink should be closed.
 *
 * This is a generic interface that other data receivers can implement.
 */
abstract class Sink<T> {
  /**
   * Adds [data] to the sink.
   *
   * Must not be called after a call to [close].
   */
  void add(T data);

/**

  • Closes the sink.
  • The [add] method must not be called after this method.
  • Calling this method more than once is allowed, but does nothing.
    */
    void close();
    }

    恩,事件发送过去之后,onListen中就可以收到,并且识别出事件,进行相应的处理,之后,stream中产生了新的数据,于是,StreamBuilder又触发了UI的更新,整个流程就跑通了。

    来一个简单的例子

    UI部分

    void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
///…
}

class CounterPage extends StatelessWidget {

Widget build(BuildContext context) {
final IncrementBloc bloc = BlocProvider.of<IncrementBloc>(context);

<span class="token keyword">return</span> <span class="token function">Scaffold</span><span class="token punctuation">(</span>
  appBar<span class="token punctuation">:</span> <span class="token function">AppBar</span><span class="token punctuation">(</span>title<span class="token punctuation">:</span> <span class="token function">Text</span><span class="token punctuation">(</span><span class="token string">'Stream version of the Counter App'</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">,</span>
  body<span class="token punctuation">:</span> <span class="token function">Center</span><span class="token punctuation">(</span>
  <span class="token comment">///注意这里,通过stream构建ui</span>
    child<span class="token punctuation">:</span> StreamBuilder<span class="token operator">&lt;</span>int<span class="token operator">&gt;</span><span class="token punctuation">(</span>
      stream<span class="token punctuation">:</span> bloc<span class="token punctuation">.</span>outCounter<span class="token punctuation">,</span>
      initialData<span class="token punctuation">:</span> <span class="token number">0</span><span class="token punctuation">,</span>
      builder<span class="token punctuation">:</span> <span class="token punctuation">(</span>BuildContext context<span class="token punctuation">,</span> AsyncSnapshot<span class="token operator">&lt;</span>int<span class="token operator">&gt;</span> snapshot<span class="token punctuation">)</span><span class="token punctuation">{</span>
        <span class="token keyword">return</span> <span class="token function">Text</span><span class="token punctuation">(</span><span class="token string">'You hit me: ${snapshot.data} times'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token punctuation">}</span>
    <span class="token punctuation">)</span><span class="token punctuation">,</span>
  <span class="token punctuation">)</span><span class="token punctuation">,</span>
  floatingActionButton<span class="token punctuation">:</span> <span class="token function">FloatingActionButton</span><span class="token punctuation">(</span>
    child<span class="token punctuation">:</span> <span class="token keyword">const</span> <span class="token function">Icon</span><span class="token punctuation">(</span>Icons<span class="token punctuation">.</span>add<span class="token punctuation">)</span><span class="token punctuation">,</span>
    onPressed<span class="token punctuation">:</span> <span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">{</span>
    <span class="token comment">///注意这里,事件发送</span>
      bloc<span class="token punctuation">.</span>incrementCounter<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token punctuation">,</span>
  <span class="token punctuation">)</span><span class="token punctuation">,</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span>

}
}

Bloc部分

class IncrementBloc{
int _counter;

//
// Stream to handle the counter,第一组stream
//
StreamController<int> _counterController = StreamController<int>();
StreamSink<int> get _inAdd => _counterController.sink;//这个sink用与给outCounter添加数据
Stream<int> get outCounter => _counterController.stream;//这个就是ui需要使用的stream

//
// Stream to handle the action on the counter,第二组stream
//
StreamController _actionController = StreamController();
StreamSink get incrementCounter => _actionController.sink;//这个暴露给外部,用户接受ui事件

IncrementBloc(){
_counter = 0;
_actionController.stream.listen(_handleLogic);
}

void _handleLogic(data){
_counter = _counter + 1;
_inAdd.add(_counter);
}
}

初次接触这种模式,你可能会稍感不适,没有任何关系,在心中把这个回路多跑即便,就清楚了,注意这里的BloC的设计上用到了两组stream,对,你没看错,是两组,两组形成了一个【闭环】,才能搞出这种【打法】。

因为第一组stream用户产生ui用的数据,第二组stream用户接受处理UI事件。

总结及个人建议

使用Bloc模式开发app的好处显而易见,大约有:

1、严重遵守了单一职责原则,代码解耦更好。

2、模块更加易于测试。

3、便面了setState的方式来触发build,可能性能更好,注意,只是可能,因为这也是大佬们说的,我并不太认可,实际上我认为,即便是使用streamBuilder,当stream有新的data时,也是触发了其包裹的组件走build的。

那么,你真的需要BloC模式吗?

1、个人觉得,非常简单的页面,使用BloC就有点过了,实际上像上面那个例子,点击次数计数,用StateFulWidget明显就是更优选择,使用BloC就有点为了模式而模式了。

2、用于不用BloC,要基于业务场景来考虑,个人觉得,对于多个UI共享一份数据的例子,就非常使用BloC模式,比如订单相关的页,购物车等等,因为订单状态的扭转,购物车物品同步,用户发送的事件相当多,这种如果使用BloC模式,显然会是目前来看的最优模式。

Redux相比大家也听过了,flutter中当然也是有的,那么,和Bloc有什么区别么?

1、个人觉得,并没有什么区别,都可以实现数据共享,大家也都能实现总线的功能,redux理解难度上,似乎还要比Bloc更加复杂点,因为他概念会多一些。

2、如果让我选择,我更加倾向于直接使用Bloc,最少的代码完成需求,比起引入一个库,话费的代价要少。

初学者的疑问

1、想bloc发送事件一定需要通过另外一个streamController么?答案是不一定,写成一个公开发送,直接操作那个数据相关的StreamController发送数据也可以,个人觉得这么写可能还更加简单呢?只是看自己以的业务逻辑吧。

2、必须要通过,final IncrementBloc bloc = BlocProvider.of<IncrementBloc>(context);获取bloc么?

我的回答是,必须有一个地方是的,就像弹吉他一样,根弦需要,其他的不需要而且不能需要,因为如果次级页面也通过这种方式获取的话,那他销毁时,dispose被回调,这个bloc也就销毁了,一级页面的bloc也就不能用了,这其实也是一个坑,很容就掉进去了,所以,区分什么时候通过final IncrementBloc bloc = BlocProvider.of<IncrementBloc>(context);获取,什么时候通过参数传递的方式传递过去,还是很重要的。

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

编辑于
7 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值