mirkaim
mirkaim

Reputation: 314

Can you access riverpod from a flutter action?

I am wanting to create an action so that the user can either click a button or hit a key to perform an update on a StateNotifier's state (and then update the ui). But I realize after I figure out how to get Actionsworking that I don't have access to WidgetRef or ref so that I can update the provider.

Is it possible to use actions with Riverpod? Would I need to send ref to the action or is that too much lifting and against the point?

class RemoveFileIntent extends Intent {
  const RemoveFileIntent();
}

class RemoveFileAction extends Action<RemoveFileIntent> {
  RemoveFileAction();

  @override
  Object? invoke(covariant RemoveFileIntent intent) {

    // update riverpod StateNotifier's state?

    return null;
  }
}

Upvotes: 0

Views: 202

Answers (1)

R&#233;mi Rousselet
R&#233;mi Rousselet

Reputation: 277527

There are two options. You could create your action in a provider, then pass the provider's Ref to the constructor of your object:

final removeFileActionProvider = Provider(RemoveFileAction.new);

class RemoveFileAction extends Action<RemoveFileIntent> {
  RemoveFileAction(this.ref);

  final Ref ref;

  @override
  Object? invoke(covariant RemoveFileIntent intent) {
    ref.read(provider).doSomething(intent);

    return null;
  }
}

Or create your action in a ConsumerWidget/Consumer/ConsumerStatefulWiget, and pass WidgetRef instead of Ref

Upvotes: 2

Related Questions