registerForRestoration method Null safety

  1. @protected
void registerForRestoration(
  1. RestorableProperty<Object?> property,
  2. String restorationId
)

Registers a RestorableProperty for state restoration.

The registration associates the provided property with the provided restorationId. If restoration data is available for the provided restorationId, the property's value is restored to the value described by the restoration data. If no restoration data is available, the property will be initialized to a property-specific default value.

Each property within a State object must be registered under a unique ID. Only registered properties will have their values restored during state restoration.

Typically, this method is called from within restoreState to register all restorable properties of the owning State object. However, if a given RestorableProperty is only needed when certain conditions are met within the State, registerForRestoration may also be called at any time after restoreState has been invoked for the first time.

A property that has been registered outside of restoreState must be re-registered within restoreState the next time that method is called unless it has been unregistered with unregisterFromRestoration.

Implementation

@protected
void registerForRestoration(RestorableProperty<Object?> property, String restorationId) {
  assert(property != null);
  assert(restorationId != null);
  assert(property._restorationId == null || (_debugDoingRestore && property._restorationId == restorationId),
         'Property is already registered under ${property._restorationId}.',
  );
  assert(_debugDoingRestore || !_properties.keys.map((RestorableProperty<Object?> r) => r._restorationId).contains(restorationId),
         '"$restorationId" is already registered to another property.',
  );
  final bool hasSerializedValue = bucket?.contains(restorationId) == true;
  final Object? initialValue = hasSerializedValue
      ? property.fromPrimitives(bucket!.read<Object>(restorationId))
      : property.createDefaultValue();

  if (!property.isRegistered) {
    property._register(restorationId, this);
    void listener() {
      if (bucket == null)
        return;
      _updateProperty(property);
    }
    property.addListener(listener);
    _properties[property] = listener;
  }

  assert(
    property._restorationId == restorationId &&
    property._owner == this &&
    _properties.containsKey(property),
  );

  property.initWithValue(initialValue);
  if (!hasSerializedValue && property.enabled && bucket != null) {
    _updateProperty(property);
  }

  assert(() {
    _debugPropertiesWaitingForReregistration?.remove(property);
    return true;
  }());
}