loading...

Upgrade to Bloc Library from v0.x to v2.x for Flutter and Angular Dart

mhadaily profile image Majid Hajian Updated on ・2 min read

There has been a great improvement to Bloc library by Felix Angelov which has been published here after a great contribution by the community for an issue on Github. This is the power of the community in order to shape a great library. So, As a community person, I love it!

Since then, I was asked several times regarding the upgrade to the new version. Although changelogs are available by Felix, I still decided to write a short blog in order to share my knowledge after upgrading to the new version on a huge codebase.

The main changes in Bloc v2.0.0 are:

1- Bloc as a Stream, that means all blocs are now Stream. Therefore, you can listen to bloc right away and it enables us to get state as the latest state available. In short, currentState in bloc is no longer makes sense instead it becomes state.

2- Bloc as a Sink, which enables us to use add on sink API in order to notify the bloc of a new event.

So, in order to make your code compatible, technically in your Bloc you need to do the following changes:

from

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  exampleMethod() {
    print(currentState);
  }
}

to

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  exampleMethod() {
    print(state);
  }
}

When you need to manipulate your state you had dispatch method where you could pass an event to, now you can simply use add instead as all blocs are now Sinks.

from

 BlocProvider.of<AnyBloc>(context).dispatch(YourEvent());

to

 BlocProvider.of<AnyBloc>(context).add(YourEvent());

and simply if you are in Bloc itself,

from

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  ExampleBloc() {
    dispatch(ExampleInitialEvent());
  }
}

to

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  ExampleBloc() {
    add(ExampleInitialEvent());
  }
}

and now if you have cleaned up your bloc by override the dispose method, you should be able to replace it with close due to the change as mentioned above. Simply like:

from

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  ExampleBloc() {
    dispatch(ExampleInitialEvent());
  }

  StreamSubscription<ExampleStream> _subscription;

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }
}

to

class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
  ExampleBloc() {
    add(ExampleInitialEvent());
  }

  StreamSubscription<ExampleStream> _subscription;

  @override
  Future<void> close() {
    _subscription.cancel();
    return super.close();
  }
}

These changes should make your code compatible with version v2.0.0.

Post your comment if you still have issues or share your experience on what you have done.

I hope this short blog can help those you have faced problems while upgrading or have worries to start upgrading.

Happy upgrading!

Discussion

pic
Editor guide