initState method

  1. @override
void initState()
override

Called when this object is inserted into the tree.

The framework will call this method exactly once for each State object it creates.

Override this method to perform initialization that depends on the location at which this object was inserted into the tree (i.e., context) or on the widget used to configure this object (i.e., widget).

If a State's build method depends on an object that can itself change state, for example a ChangeNotifier or Stream, or some other object to which one can subscribe to receive notifications, then be sure to subscribe and unsubscribe properly in initState, didUpdateWidget, and dispose:

  • In initState, subscribe to the object.
  • In didUpdateWidget unsubscribe from the old object and subscribe to the new one if the updated widget configuration requires replacing the object.
  • In dispose, unsubscribe from the object.

You should not use BuildContext.dependOnInheritedWidgetOfExactType from this method. However, didChangeDependencies will be called immediately following this method, and BuildContext.dependOnInheritedWidgetOfExactType can be used there.

Implementations of this method should start with a call to the inherited method, as in super.initState().

Implementation

@override
void initState() {
  super.initState();

  /// Set the state name if the widget is a NyStatefulWidget
  if (widget is NyStatefulWidget) {
    final _controller = (widget as NyStatefulWidget).controller;
    if (_controller.context == null) {
      _controller.construct(context);
    }

    /// Take the name from the widget, so this state listens on the name its
    /// senders use. A `name` or `path` given to this state wins over it.
    stateName ??= (widget as NyStatefulWidget).state;

    /// Point the controller at this page, so `controller.refreshPage()` and
    /// the other controller state helpers address the page the controller is
    /// being used from. A controller declared as a singleton is shared by
    /// every page that asks for it, so the name an earlier page left behind
    /// is replaced rather than kept.
    _controller.state = stateName;
  }

  /// Set the state name from a NyStateManaged widget that declares its baseState
  if (widget is NyStateManaged) {
    final managed = widget as NyStateManaged;
    if (managed.baseState != null) {
      stateName = managed.stateKey;
    }
  }

  if (allowStateUpdates && eventBus != null) {
    _restoreStateFromHistory();
    _subscribeToStateUpdates();
  }

  if (!shouldLoadView) {
    init();
    hasInitComplete = true;
    return;
  }

  awaitData(
    perform: () async {
      await init();
      hasInitComplete = true;
    },
    shouldSetStateBefore: false,
  );
}