Home > OS >  Convenient way to share BLoC between multiple screen
Convenient way to share BLoC between multiple screen

Time:08-03

I am looking for the most convenient way to share bloc in different screens/pages without providing at top of the material app. For example I have a Customer bloc, which is required in CustomerListScreen and CustomerDetailsScreen. The bloc is created in CustomerListScreen and passed it to the CustomerDetailsScreen while navigating.

Navigator.context, MaterialPageRoute(builder: (context) => CustomerDetailsScreen(context.read<CustomerBloc>())));

This is the procedure I am following right now. Looking for any better approach available out there..

CodePudding user response:

Use BlocProvider.value.

BlocProvider can be used to provide an existing bloc to a new portion of the widget tree. This will be most commonly used when an existing bloc needs to be made available to a new route. In this case, BlocProvider will not automatically close the bloc since it did not create it.

BlocProvider.value(
  value: context.read<CustomerBloc>(),
  child: CustomerDetailsScreen(),
);

CodePudding user response:

You could make the Bloc a required field of the page, something like this:

class CustomerDetailsScreen extends StatelessWidget { 
  CustomerDetailsScreen(this.mybloc);

  final Bloc mybloc;

  @override
  Widget build(BuildContext context) {
    return  BlocProvider.value(
      value: mybloc,
      child: Text('Body...'),
    );
  }
}

Now even if you use a package like AutoRoute you will still be able to provide the bloc to the page route

  • Related