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

Created on 10 Oct 2019  路  5Comments  路  Source: felangel/bloc

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

dependency enhancement

Most helpful comment

@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 馃憤

All 5 comments

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

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.

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>

@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 馃憤

Well, here goes another Dart flaw to my list.

Was this page helpful?
0 / 5 - 0 ratings