slot<T> method

  1. @override
RefSlot<T> slot<T>(
  1. String name, {
  2. required T initial,
  3. T caster(
    1. dynamic value
    )?,
})
override

(en) Returns a typed state slot associated with the given name.

If the slot does not exist yet, a new slot is created and its type is fixed at creation time. Once fixed, the slot's type cannot be changed. Accessing the same slot name with a different type will throw an error.

If initial is specified and a value does not already exist, initial is set as the initial value when the slot is created.

If a value already exists initial is ignored.

(ja) 指定された名前に対応する、型付きの状態スロットを取得します。 このクラスではディープコピーによるガードがありませんが、 参照値をそのまま利用できるスロットが返されます。 つまり、ディープコピーできないクラスも管理対象にすることができます。

スロットがまだ存在しない場合は新しく作成され、 その作成時点でスロットの型が確定します。 一度確定したスロットの型は変更できません。 同じ名前のスロットを異なる型で取得しようとするとエラーになります。

initial が指定されており、かつ値がまだ存在しない場合のみ、 スロット作成時に初期値としてinitialが設定されます。

すでに値が存在する場合 initial は無視されます。

  • name : The slot name. This name will be thrown if an error occurs, so do not put any confidential information in it.
  • initial : Initial value of the slot.
  • caster : This value has no effect for this class.

slot creation example:

final refState = RefAppState();
final a = state.slot<ClassA>('a', initial: ClassA());

Implementation

@override
RefSlot<T> slot<T>(
  String name, {
  required T initial,
  T Function(dynamic value)? caster,
}) {
  final existing = _slots[name];
  if (existing != null) {
    if (existing is! RefSlot<T>) {
      throw StateError(
        'Slot "$name" already bound to '
        '${existing.runtimeType}, not RefSlot<$T>',
      );
    }
    // 既に値があり、initial は無視
    return existing;
  }
  final slot = RefSlot<T>(name, this);
  _slots[name] = slot;
  // 初期値をセット
  if (!_data.containsKey(name)) {
    setInitial(slot, initial);
  }
  return slot;
}