'Is this the correct way to use Bloc in flutter?
How to use Bloc in flutter. What is the best way to use it? to wrap the whole app with blocprovider
?
runApp(
RepositoryProvider(
create: (context) => API(),
child: MultiBlocProvider(
providers: [
BlocProvider<GlobalViewBloc>(
lazy: false,
create: (BuildContext context) =>
GlobalViewBloc(context.read<API>()),
),
BlocProvider<CountryDetailViewBloc>(
lazy: false,
create: (BuildContext context) =>
CountryDetailViewBloc(context.read<API>()),
),
],
child: MaterialApp(
home:MyApp(),
),
),
));
Solution 1:[1]
there are two ways of accessing bloc:
1 - global declaration
you declare a bloc variable inside your bloc and all widgets and whole app will have access to that variable. like this:
final bloc = YourBloc();
2 - using provider
in this declaration you have to define the provider in the highest widget which you want having the access to bloc and all of its children will have access to that bloc:
class WD extends StatelessWidget {
@override
Widget build(BuildContext context) {
final bloc = YourBlocProvider.of(context);
/....
);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Benyamin |