Bloc: A few questions

Created on 12 Jun 2020  Â·  2Comments  Â·  Source: felangel/bloc

Hi Felix! I truly appreciate your efforts in this amazing package! I have three questions if you don’t mind lol :)

1- So I am trying to access my shared preference anywhere in my app so I can easily save/get prefs. Would this be a good use of RepositoryProvider or do you recommend I make a singleton class instead?

2- If I have 2 blocs that use the same repository, should my setup be like:
RepositoryProvider —> MultiBlocProvider (as a child to RepositoryProvider) ? Can I pass my repository instance into the multiblocprovider?

3- My final question would be do we have a widget that can “listen” to a bloc? One of my Blocs downloads videos and I somehow need to display the progress in my UI.

Thank you very much for your time!

question

Most helpful comment

@RollyPeres Wow thank you very very very much! Couldn’t ask for more! Made my day :D!

All 2 comments

Hi @DeadlyMissile đź‘‹

1 - you can definitely treat shared preferences as a data source and use it within a repository that you provide globally, e.g.:

Future<void> main() async {
  runApp(
  SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
      RepositoryProvider<SharedPreferencesRepository>(
        create: (_) => SharedPreferencesRepository(sharedPreferences: sharedPreferences),
        child: MyApp(),
      ),
    );
}

You could also use HydratedBloc and keep your preferences on it's state and the persistence will be taken care of for you.

2 - Yes, e.g.:

RepositoryProvider<UserRepository>(
      create: (_) => UserRepository(),
      child: MultiBlocProvider(
        providers: [
          BlocProvider<AuthBloc>(
            create: (_) => context.repository<UserRepository>(),
          ),
          BlocProvider<LoginBloc>(
            create: (_) => context.repository<UserRepository>(),
          ),
        ],
        child: const MyApp(),
      ),
    ),

3 - You can use BlocBuilder to build your UI based on the download progress which you would store on your bloc state and yield a new state with the new progress whenever the progress is updated. Have a look at https://github.com/felangel/bloc/issues/1218#issuecomment-634537394 for a somewhat similar scenario.

Hope that helps 👍

@RollyPeres Wow thank you very very very much! Couldn’t ask for more! Made my day :D!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

timtraversy picture timtraversy  Â·  3Comments

komapeb picture komapeb  Â·  3Comments

shawnchan2014 picture shawnchan2014  Â·  3Comments

ricktotec picture ricktotec  Â·  3Comments

1AlexFix1 picture 1AlexFix1  Â·  3Comments