Reputation: 407
Error: I/flutter ( 5919): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════ I/flutter ( 5919): The following assertion was thrown building Builder: I/flutter ( 5919): BlocProvider.of() called with a context that does not contain a Bloc of type Bloc. I/flutter ( 5919): No ancestor could be found starting from the context that was passed to I/flutter ( 5919): BlocProvider.of>(). I/flutter ( 5919):
This can happen if the context you used comes from a widget above the BlocProvider. I/flutter ( 5919): The context used was: BlocBuilder, dynamic>(dirty, state: I/flutter ( 5919): _BlocBuilderBaseState, dynamic>#55a7d(lifecycle state: created)) I/flutter ( 5919): The relevant error-causing widget was: I/flutter ( 5919): MaterialApp /lib/main.dart:35:12
Here's my main
void main() {
final StorageRepository storageRepository = StorageRepository();
final AuthenticationRepository authenticationRepository =
AuthenticationRepository();
runApp(BlocProvider<AuthenticationBloc>(
create: (_) => AuthenticationBloc(
authenticationRepository: authenticationRepository,
storageRepository: storageRepository),
child: MyApp()));
}
MaterialApp Widget
MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.deepPurple),
home: BlocBuilder(
builder: (context, state) {
print(state);
if (state is Authenticated) {
return MainPage();
} else if (state is Unauthenticated) {
return LoginPage();
} else if (state is Uninitialized) {
return SplashScreen();
}
return Container();
},
),
Upvotes: 4
Views: 4282
Reputation: 34270
As the error, itself suggest BlocProvider
not accessing the right context
to use the bloc
MultiBlocProvider
provides the ability to add multiple providers which then can get the right context access as MultiBlocProvider
converts the BlocProvider
list into a tree of nested
BlocProvider
widgets.
MultiBlocProvider(
providers: [
BlocProvider<YourBloc>(
create: (BuildContext context) =>)
],
child: MaterialApp(
home: BlocBuilder<YourBloc, YourState>(
Upvotes: 0
Reputation: 2864
You forget to give the Bloc and State type to the BlocBuilder Widget
MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.deepPurple),
/// You need to specify the type here,
/// that's why you got error Bloc<dynamic, dynamic>
home: BlocBuilder<AuthenticationBloc, AuthenticationState>(
builder: (context, state) {
print(state);
if (state is Authenticated) {
return MainPage();
} else if (state is Unauthenticated) {
return LoginPage();
} else if (state is Uninitialized) {
return SplashScreen();
}
return Container();
},
),
Upvotes: 5