Where should I initialize the blocs in flutter_bloc

2k views Asked by At

I am using Flutter_bloc package to work with bloc pattern in flutter, but i am wondering if it is a good practice to use a MultiBlocProvider inside main function and add all of my blocs in there like this:

  void main()async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(Mafqood());
}

class Mafqood extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
       return MultiBlocProvider(
         providers : [
           BlocProvider<AuthBloc>(
           create:  (context) => AuthBloc(AuthInitialState(), AuthRepository()),
          ),

           BlocProvider<LoginBloc>(
             create: (context) => LoginBloc(LoginInitialState(), AuthRepository()),
           ),

           BlocProvider<ProfileBloc>(
             create:  (context) => ProfileBloc(ProfileInitialState(), AuthRepository()),
           ),

         ],
         child: MaterialApp(

or it is better to add the bloc just where I need it? and why? Thanks in advance.

2

There are 2 answers

0
Akif On

You should use MultiBlocProvider inside the main function as you did. This is the best practice. And this is the goal of the providers.

Edit:

Now I realized that there is another answer here.

0
Shady Mohamed Sherif On

The main usage of MultiBlocProvider is using the bloc object in different places inside your application before you had to define which bloc depends on another bloc.

If you have an app that each screen use its own bloc, then you don't have a need for MultiBlocProvideras you can creat the bloc in the build function of the screen

class ParentScreen extends StatelessWidget {
  const ParentScreen ({Key? key, this.data}) : super(key: key);
  final data;

  @override
  Widget build(BuildContext context) {
    return BlocProvider<MyBloc>(
        create: (_) => MyBloc()),
        child: MyScreenBody());
  }
}
Class MyScreenBody extends StatefulWidget {
  const MyScreenBody({Key? key}) : super(key: key);

  @override
  _MyScreenBodyState createState() => _MyScreenBodyState();
}

class _MyScreenBodyState  extends State<MyScreenBody> {
  @override

  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
      return Scaffold(
            body: BlocBuilder<MyBloc, MyState>(
              builder: (context, state) {
            return //... your code
            }
          )
        );
  }