Kenny
Kenny

Reputation: 33

Mutable variable in a Custom Class Provider Riverpod Flutter

I kinda new to Flutter and I'm using Riverpod. Is it okay (good) to have a mutable variable inside a class that I pass in using Provider?

My Provider

final groupControllerProvider = Provider<GroupController>((ref) {
  return GroupController();
});

Custom Class

class GroupController {
  List<Map<String, dynamic>>? myVariable;

  GroupController();

  Future<void> toDoWithMyVar() async {
    myVariable = ...;
  }
}

If its not good, what is the alternative? Thanks

Upvotes: 3

Views: 365

Answers (1)

Ruble
Ruble

Reputation: 4844

If your class is just a service/repository that won't be involved in updating state and rebuilding widgets, then it's wise to use a Provider for graceful dependency injection.

If your variable myVariable will be some state, based on which your widgets should be rebuilt, then

  • in the simplest case use StateProvider | FutureProvider
  • in case your state needs complex/several methods to change it, then use (Async)NotifierProvider

In the latter case, your code will look something like this:

final variableProvider = NotifierProvider<TodosNotifier, List<Map<String, dynamic>>?>(VariableNotifier.new);

class VariableNotifier extends Notifier<List<Map<String, dynamic>>?> {

  @override
  List<Map<String, dynamic>>? build() {
    return null;
  }

  Future<void> toDoWithMyVar() async {
    state = ...;
  }

You should probably also look into packages like freezed, which allow you to conveniently manage immutable objects. The fact is that for these providers to work correctly, your state must be immutable with a correctly redefined hashcode|==

Upvotes: 2

Related Questions