StateNotifierProvider<NotifierT extends StateNotifier<T>, T> constructor

StateNotifierProvider<NotifierT extends StateNotifier<T>, T>(
  1. NotifierT _createFn(
    1. StateNotifierProviderRef<NotifierT, T> ref
    ), {
  2. String? name,
  3. Iterable<ProviderOrFamily>? dependencies,
  4. @Deprecated('Will be removed in 3.0.0') Family<Object?>? from,
  5. @Deprecated('Will be removed in 3.0.0') Object? argument,
  6. @Deprecated('Will be removed in 3.0.0') DebugGetCreateSourceHash? debugGetCreateSourceHash,
})

Creates a StateNotifier and exposes its current state.

This provider is used in combination with package:state_notifier.

Combined with StateNotifier, StateNotifierProvider can be used to manipulate advanced states, that would otherwise be difficult to represent with simpler providers such as Provider or FutureProvider.

For example, you may have a todo-list, where you can add and remove and complete a todo. Using StateNotifier, you could represent such state as:

class TodosNotifier extends StateNotifier<List<Todo>> {
  TodosNotifier(): super([]);

  void add(Todo todo) {
    state = [...state, todo];
  }

  void remove(String todoId) {
    state = [
      for (final todo in state)
        if (todo.id != todoId) todo,
    ];
  }

  void toggle(String todoId) {
    state = [
      for (final todo in state)
        if (todo.id == todoId) todo.copyWith(completed: !todo.completed),
    ];
  }
}

Which you can then pass to a StateNotifierProvider like so:

final todosProvider = StateNotifierProvider<TodosNotifier, List<Todo>>((ref) => TodosNotifier());

And finally, you can interact with it inside your UI:

Widget build(BuildContext context, WidgetRef ref) {
  // rebuild the widget when the todo list changes
  List<Todo> todos = ref.watch(todosProvider);

  return ListView(
    children: [
      for (final todo in todos)
        CheckboxListTile(
           value: todo.completed,
           // When tapping on the todo, change its completed status
           onChanged: (value) => ref.read(todosProvider.notifier).toggle(todo.id),
           title: Text(todo.description),
        ),
    ],
  );
}

Implementation

StateNotifierProvider(
  this._createFn, {
  super.name,
  super.dependencies,
  @Deprecated('Will be removed in 3.0.0') super.from,
  @Deprecated('Will be removed in 3.0.0') super.argument,
  @Deprecated('Will be removed in 3.0.0') super.debugGetCreateSourceHash,
}) : super(
        allTransitiveDependencies:
            computeAllTransitiveDependencies(dependencies),
      );