Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a way to know if a provider's value has been created #886

Closed
ChreSyr opened this issue Sep 10, 2024 · 2 comments
Closed

Add a way to know if a provider's value has been created #886

ChreSyr opened this issue Sep 10, 2024 · 2 comments
Assignees
Labels
enhancement New feature or request question Further information is requested

Comments

@ChreSyr
Copy link

ChreSyr commented Sep 10, 2024

In my app, i have a FavoritesCubit that streams data from my database. Every time the UserCubit changes, the stream of FavoritesCubit is canceled and then restarted. For this, i use BlocListener, from flutter_bloc package.

FavoritesCubit contains data that are only accessible through a secondary page in my app, it is not on the home page.

The thing is, when i launch my app, the BlocListener instantly prevents my FavoritesCubit of the changes. So the BlocProvider instantly creates the FavoritesCubit, and dependency injection is useless.

I wish i could detect, from the BlocListener, if the FavoritesCubit has already been created or not. This way, it will only be updated when needed.

I think something like this would be enough :

class Provider<T> extends InheritedProvider<T> {
  static bool hasValue<T>(BuildContext context) => _inheritedElementOf<T>(context).hasValue;
}

So i would write :

BlocListener<UserCubit, UserModel?>(
  listenWhen: (previous, current) => previous?.favorites != current?.favorites,
  listener: (context, user) {
    if (Provider.hasValue<FavoritesCubit>(context)) {
      context
          .read<FavoritesCubit>()
          .onUserFavoritesChanged(user?.favorites ?? []);
    }
  },
),

What do you guys think about it ?

@rrousselGit
Copy link
Owner

It's already supported, through nullable values.

You can do:

final exists = context.read<T?>() != null;

If the value doesn't exist, when using a nullable value, you'll get null

@rrousselGit rrousselGit added question Further information is requested and removed needs triage labels Sep 10, 2024
@ChreSyr
Copy link
Author

ChreSyr commented Sep 11, 2024

Thanks !!

@ChreSyr ChreSyr closed this as completed Sep 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants