update<R extends T?> method

void update<R extends T?>(
  1. dynamic mutator(
    1. R s
    ), {
  2. bool shouldNotify = true,
  3. String? tag,
})

Safer update for nullable injected types. Always specify the generic parameter explicitly matching T?.

Implementation

void update<R extends T?>(
  dynamic Function(R s) mutator, {
  bool shouldNotify = true,
  String? tag,
}) {
  final bool rIsNullable = null is R;
  assert(rIsNullable == true,
      'Type mismatch: update<$R> called on Injected<$T?>. The type parameter must be nullable (T?).');

  final R stateAsR = state as R; // cast current state for mutator
  final result = mutator(stateAsR);

  if (result is T || result == null) {
    try {
      state = result;
    } catch (e) {
      log('StateRebuilderExtension.update error: $e');
    }
    if (shouldNotify && WidgetsBinding.instance.isRootWidgetAttached) {
      _TagRegistry.set(this, tag);
      notify();
      WidgetsBinding.instance
          .addPostFrameCallback((_) => _TagRegistry.clear(this));
    }
  }
}