LoginSignup
1
1

More than 1 year has passed since last update.

[Flutter]BLoC 7.0系から8.0系の破壊的変更に対応した話(mapEventToState廃止)

Last updated at Posted at 2022-09-15

はじめに

私の携わっているプロジェクトではflutter_blocを採用しており、
今回7系から8系にアップデートを行いました。

元々v7.0.0を利用しておりましたが8系で1点破壊的変更が入っており、
対応に関する日本語での記事が少なかった為、今回共有をさせて頂きます。

破壊的変更点 (mapEventToState廃止)

v7.0.0を利用していた当初、何かしらのEventを発火させた後にBLoCクラス内ではmapEventToStateを用いて各種Eventのハンドリングを行なっておりました。
このmapEventToStatev7.2.0から非推奨になりv8.0.0以降は廃止となるようです。

In bloc v7.2.0, mapEventToState was deprecated in favor of on. mapEventToState will be removed in bloc v8.0.0.
https://bloclibrary.dev/#/migration?id=v720

廃止後はon<Event>APIを用いてEventのハンドリングを行う必要があるとのことで、
今回はmapEventToStateからon<Event>APIへの移行を主に対応いたしました。

補足

公式曰くDartの問題でネストした非同期ジェネレータ(async*)を扱うときにstate値の不確実性問題(?)があったようで、その問題に対応するために、on<Event>APIを用いたとのこと。

The on API was introduced as part of [Proposal] Replace mapEventToState with on in Bloc. Due to an issue in Dart it's not always obvious what the value of state will be when dealing with nested async generators (async*). Even though there are ways to work around the issue, one of the core principles of the bloc library is to be predictable. The on API was created to make the library as safe as possible to use and to eliminate any uncertainty when it comes to state changes.

対応内容

基本は公式に沿って対応しています。
mapEventToStateを廃止し、各BLoCクラスの下にon<EVENT>のハンドリングを記述し、
yieldでstateを返却していた部分をemit()に書き換えるだけです。
下記は公式を模したもの。


before v7.0.0

abstract class TestEvent {}
class HogeEvent extends TestEvent {}
class FugaEvent extends TestEvent {}

class HogeBloc extends Bloc<TestEvent, HogeState> {
  HogeBloc() : super();

  @override 
  Stream<HogeState> mapEventToState(event) async* { <--ここが消える 
    if (event is HogeEvent) {
      yield HogeState();
    }
    if (event is FugaEvent) {
      yield HogeState();
      final response = await _hogeRepository.fetch();
      yield HogeState(response);
    }
  }
}

after v8.0.0

abstract class TestEvent {}
class HogeEvent extends TestEvent {}
class FugaEvent extends TestEvent {}

class HogeBloc extends Bloc<TestEvent, HogeState> {
  HogeBloc() : super() {
      on<HogeEvent>((event, emit) => emit(HogeState())); <--ここが追加される。  
      on<FugaEvent>((event, emit) async { <--こっちも。
        emit(HogeState());
        final response = await _hogeRepository.fetch();
        emit(HogeState(response));
      });
  }
}

まとめ

flutter_blocの7系を使っているPJは全てのmapEventToStateを書き換える必要がある為、
PJによっては全ての機能を再テストする必要が出てくる可能性があるのではないでしょうか…?
かなりクリティカルではありますがコード修正の難易度自体はそこまで大きくないと思いますので、
早めに対応されることをオススメします。

参考サイト

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1