bloc icon indicating copy to clipboard operation
bloc copied to clipboard

BlocBuilder doesn't need to explicitly provide the State type again

Open bigworld12 opened this issue 6 years ago • 5 comments

i am not sure why we need to pass the state type again in BlocBuilder. currently we would write

BlocBuilder<BlocA,StateA>(
builder: (BuildContext context, StateA state) => ...
)

but why can't we remove the StateA, and instead write

BlocBuilder<BlocA>(
builder: (BuildContext context, StateA state) => ...
)

since BlocA already defines the state type. and checking the definition here https://github.com/felangel/bloc/blob/805cf865fe0972e7f1bd24f08598d624066434fb/packages/flutter_bloc/lib/src/bloc_builder.dart#L18

why can't we just write it as

class BlocBuilder<B extends Bloc<dynamic, S>> extends BlocBuilderBase<B, S>

i am not sure if this is a limitation in dart, but it's annoying that i have to pass the state type again for every BlocBuilder

bigworld12 avatar Oct 10 '19 05:10 bigworld12

Hi @bigworld12 👋 Thanks for opening an issue!

Unfortunately, I don't think this is possible.

class BlocBuilder<B extends Bloc<dynamic, S>> extends BlocBuilderBase<B, S>

^ won't compile because you need to define S (unless I'm missing something).

I totally agree that it would be ideal not to have to pass State and that dart should be able to infer the type.

Screen Shot 2019-10-10 at 1 08 25 AM

felangel avatar Oct 10 '19 06:10 felangel

Maybe DartLangSpec can help, page 61, chapter 14 Generics, https://dart.dev/guides/language/specifications/DartLangSpec-v2.2.pdf.


image image


From the text above (and rest of the chapter) I assume, that because in class BlocBuilder<B extends Bloc<dynamic, S>> there is no type parameter S, it's only something from the upper bound from the type parameter B, you cannot pass it to extend clause of the class ... extends BlocBuilderBase<B, S>.

Not sure if I get it right, tho.

tenhobi avatar Oct 11 '19 06:10 tenhobi

yeah i think this is a language limitation, c# also has the same problem valid :

class BlocBuilder<TBloc,TState> where TBloc : Bloc<object,TState>

invalid:

class BlocBuilder<TBloc> where TBloc : Bloc<object,TState>

bigworld12 avatar Oct 11 '19 16:10 bigworld12

@tenhobi yeah exactly. I think Dart just has no way to know what the generic type S is unless you define it unfortunately. @bigworld12 thanks for opening the issue 👍

felangel avatar Oct 11 '19 16:10 felangel

Well, here goes another Dart flaw to my list.

mateusfccp avatar Jul 06 '20 10:07 mateusfccp