use<T> method

  1. @override
  2. @nonVirtual
T use<T>(
  1. Hook<T> hook
)
override

Registers hook in this HookContext and returns its value.

This method can only be called during build of this HookContext, otherwise an exception will be thrown. After the first build, all subsequent builds must call this method in the same order, with Hooks of the same type.

Implementation

@override
@nonVirtual
T use<T>(Hook<T> hook) {
  if (_isFirstBuild) {
    final state = _createState(hook);
    _index++;
    _hooks.add(state);
    state.init();
    return state.build();
  } else {
    var isUpdate = true;
    assert(() {
      if (_index == _hooks.length) {
        if (_debugWillReassemble) {
          isUpdate = false;
          _hooks.add(_createState(hook));
        } else {
          throw FlutterError.fromParts([
            ErrorSummary("Trying to add a hook after the first build"),
            ErrorDescription("New hooks cannot be added after the first build"),
            ErrorHint("To dynamically change hooks during build, use control flow hooks"), // TODO add article link
            DiagnosticableNode(name: "hook", value: hook, style: null),
            DiagnosticableTreeNode(name: "context", value: this, style: null),
          ]);
        }
      }
      if (_hooks[_index].hook.runtimeType != hook.runtimeType) {
        if (_debugWillReassemble) {
          _hooks[_index].dispose();
          _hooks[_index] = _createState(hook);
          isUpdate = false;
        } else {
          throw FlutterError.fromParts([
            ErrorSummary("Trying to change hook type after the first build"),
            ErrorDescription("Hook types cannot be changed after the first build"),
            ErrorHint("To dynamically change hooks during build, use control flow hooks"), // TODO add article link
            DiagnosticableNode(name: "old hook", value: _hooks[_index].hook, style: null),
            DiagnosticableNode(name: "new hook", value: hook, style: null),
            DiagnosticableTreeNode(name: "context", value: this, style: null),
          ]);
        }
      }
      return true;
    }());
    final state = _hooks[_index++] as HookState<T, Hook<T>>;
    final oldHook = state.hook;
    state.hook = hook;
    if (isUpdate) {
      state.didUpdate(oldHook);
    } else {
      state.init();
    }
    return state.build();
  }
}