0

How can we access a method from the being wrapped riverpod provider?

ContentProvider can access user value from UserProvider by using "watch". There is no problem for this direction. On the other hand, UserProvider also needs access to the methods of ContentProvider. So bidirectional communication is required.

For this case, I need to call deleteContents method from UserProvider.

I don't prefer to merge them to keep logic safe.

class ContentProviderNotifier extends ChangeNotifier {

  final User? currentUser;
  ContentProviderNotifier({required this.currentUser});
  
  addContent(Content content) {    
    content.user = currentUser?.name;
    ...
  }

  deleteContents() {
    ...
  }

}

final contentProvider = ChangeNotifierProvider<ContentProviderNotifier>(
  (ref) {
    final user = ref.watch(userProvider).currentUser;
    return ContentProviderNotifier(currentUser: user);
  },
);
class UserProviderNotifier extends ChangeNotifier {

  UserProviderNotifier();
  User? currentUser;

  deleteUsers(){
     // here to call a method from contentProvider
     deleteContents();
  }

}

final userProvider = ChangeNotifierProvider<UserProviderNotifier>(
  (ref) {
    return UserProviderNotifier();
  },
);

If I try to feed UserProvider with ContentProvider like this

final userProvider = ChangeNotifierProvider<UserProviderNotifier>(
  (ref) {
    final content = ref.watch(contentProvider); // <----
    return UserProviderNotifier(content);
  },
);

But I know, It won't make sense.

The type of 'userProvider' can't be inferred because it depends on itself through the cycle: contentProvider, userProvider. Try adding an explicit type to one or more of the variables in the cycle in order to break the cycle.darttop_level_cycle

1 Answers1

0

You can create UserProviderNotifier so it takes ref as an input, like this:

class UserProviderNotifier extends ChangeNotifier {

  UserProviderNotifier(this.ref);

  final Ref ref;

  deleteUsers() {
    // here to call a method from contentProvider
    ref.watch(contentProvider.notifier).deleteContents();
  }

}

final userProvider = ChangeNotifierProvider<UserProviderNotifier>(
      (ref) {
    return UserProviderNotifier(ref);
  },
);

This section of the Riverpod docs mentions this is a common use-case.

Code on the Rocks
  • 11,488
  • 3
  • 53
  • 61