flutterdartsetstateblocstate-management

Flutter: State management


I've seen many tutorials praising Bloc State management, what is so special about it and should I learn it as a beginner? if not is there any beginner friendly state management technique?


Solution

  • BLoC/Cubit

    BLoC is great for complex state management for complex apps. However, inside the BLoC library there's a simpler way of managing state that's called Cubit (Cubit is sort of a subset of BLoC). Cubit is largely the same as BLoC except:

    1. less boilerplate
    2. doesn't use 2-way streams

    This renders it much easier to learn, and a fantastic stepping-stone into a full-out BLoC driven state management solution.

    Currently, my team and I are building a very complex app, and we use the principle: use Cubits, unless there's a specific reason to use a BLoC. This has worked well for us (90% of our app is run with Cubit, 10% with BLoC).


    In relation to other state management techniques, most people are probably going to recommend Provider or Riverpods (Riverpods = Provider on steroids). They are easier to learn than Cubit/BLoC — except only for simple cases (a few page app). Once your app gets complex (authentication, feeds, api calls, etc.) a Cubit/BLoC-based architecture is going to scale better and be much cleaner.

    Additionally, the most-used state management system for production-level Flutter apps is BLoC/Cubit. So, if you're looking for a marketable skill, I'd default to that.

    Helpful links:

    Example app (understanding this will help you a lot):

    Here's a simple 1-feature app I made as a proof of concept to show how Cubit specifically works. Read the project's README.md for context (star it? 😉).

    Conclusion:

    Provider, GetX, Riverpods, etc. are all easier to learn and contain less boilerplate than BLoC, except they won't scale as well when your app gets more complex.

    To help combat the boilerplate/complexity problem of BLoC, use Cubits instead of BLoCs in your design unless you have a specific need for BLoCs.


    New answer:

    I recommend just using Trent (https://pub.dev/packages/trent) for state management. It's like BLoC, but simpler. Lots of examples in the README on GitHub. Full disclosure: I made it.