skip to Main Content

Suppose I have a create invoice screen which have different sections. Like customer details, bill to , ship to, list of product, payment details, tax section, Other charges section. Do I use seprate bloc for each section or one bloc for all sections? If I use one bloc then how to implement blocbuilder build method since a lots of state will be there. If I use multiple bloc then how can get all data from different bloc to submit on server?

I am using bloc with freezed.

2

Answers


  1. In this case the better option is that you have a multibloc provider when you intance you provider change a multibloc of this form you coulded do uses the multi bloc in only view

    MultiBlocProvider(
            providers: [
              BlocProvider(
                create: (context) => BlocA(),
              ),
              BlocProvider(
                create: (context) => BlocB(),
              ),
              BlocProvider(create: (context) => BlocC())
            ],
            child: const HomeScreen(),
          );
    

    and you can used it like this

    context.read<TransactionsBloc>()..add(const GetTransactionsItems())
    
    Login or Signup to reply.
  2. it depends on your requirements.
    you have Invoice screen with different sections like customer details, bill to, ship to, list of product, payment details, tax section and other. so main reason to extract logic for some section in to separate bloc is if you use it in some other place in your app. for example, if you use Payment details in profile or separate PaymentScreen, or else where, it is good to have separate PaymentsBloc in this case.

    class YourApp extends StatefulWidget {
      const YourApp({super.key});
    ...
    class _YourAppState extends ...
      @override
      Widget build(BuildContext context) => 
        MultiBlocProvider(
            providers: [
              BlocProvider<PaymentBloc>(
                create: (_) => PaymentBloc(),
              ),
              BlocProvider<InvoiceBloc>(
                create: (context) => InvoiceBloc(),
              ),
           child: MaterialApp(
              debugShowCheckedModeBanner: false,
              theme: AppTheme.themeData(),
              onGenerateRoute: _routeBuilder.onGenerateRoute,
            ),
        ...
    

    and then in InvoicScreen

      @override
      Widget build(BuildContext context) =>
          BlocBuilder<InvoiceBloc, InvoiceState>(
        builder: (context, invoiceState) => Scaffold(
        ...
        //and then maybe you have some view part that shoud be 
        //rebuilded on PaymentState
    
        BlocBuilder<PaymentBloc, PaymentState>(
         builder: (context, paymentState) {
              return Text(..some data from paymentState..)
        ...
    

    You are free to add more blocs to separate other sections.
    more info in documentation.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search