bloc icon indicating copy to clipboard operation
bloc copied to clipboard

feat(flutter_bloc): disallow providing a bloc via RepositoryProvider

Open felangel opened this issue 3 years ago • 2 comments

I spent a ridiculous amount debugging a scenario where a context.select never updated its widget, only to find out that the Bloc it was accessing was registered through a RepositoryProvider rather than a BlocProvider. The main issue why I didn't figure it out sooner was that the context.select in this case still works... only like a context.read 😅 do you think making this at least a runtime error, if not possible as compile-time, would be an option?

Originally posted by @Lootwig in https://github.com/felangel/bloc/issues/3054#issuecomment-991817877

felangel avatar Dec 15 '21 22:12 felangel

A temporary solution would be to do as follows:

  RepositoryProvider({
    Key? key,
    required Create<T> create,
    Widget? child,
    bool? lazy,
  })  : assert(
          T is! BlocBase,
          'Use BlocProvider to provide instances of type $T',
        ),
        super(
          key: key,
          create: create,
          dispose: (_, __) {},
          child: child,
          lazy: lazy,
        );

However, this results in a runtime issue. It would be technically a breaking change for those users who are incorrectly using the API.

A better solution would be relying on custom lint rules. If so this can be considered as BLOCKED until the dart language supports custom lint rules.

alestiago avatar Jan 27 '22 17:01 alestiago

May be custom class (but need implementation for static checking), eg. :

void main() {
  if (kDebugMode) {
    BlocUtils.ensureBlocProvidedViaBlocProvider();
  }
}

? 😅

erlangparasu avatar Jan 20 '24 12:01 erlangparasu