of<T extends Model> static method

T of<T extends Model>(
  1. BuildContext context, {
  2. bool rebuildOnChange = false,
})

Finds a Model provided by a ScopedModel Widget.

Generally, you'll use a ScopedModelDescendant to access a model in the Widget tree and rebuild when the model changes. However, if you would to access the model directly, you can use this function instead!

Example

final model = ScopedModel.of<CounterModel>();

If you find yourself accessing your Model multiple times in this way, you could also consider adding a convenience method to your own Models.

Model Example

class CounterModel extends Model {
  static CounterModel of(BuildContext context) =>
      ScopedModel.of<CounterModel>(context);
}

// Usage
final model = CounterModel.of(context);

Listening to multiple Models

If you want a single Widget to rely on multiple models, you can use the of method! No need to manage subscriptions, Flutter takes care of all of that through the magic of InheritedWidgets.

class CombinedWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final username =
      ScopedModel.of<UserModel>(context, rebuildOnChange: true).username;
    final counter =
      ScopedModel.of<CounterModel>(context, rebuildOnChange: true).counter;

    return Text('$username tapped the button $counter times');
  }
}

Implementation

static T of<T extends Model>(
  BuildContext context, {
  bool rebuildOnChange = false,
}) {
  var widget = rebuildOnChange
      ? context.dependOnInheritedWidgetOfExactType<_InheritedModel<T>>()
      : context
          .getElementForInheritedWidgetOfExactType<_InheritedModel<T>>()
          ?.widget;

  if (widget == null) {
    throw ScopedModelError();
  } else {
    return (widget as _InheritedModel<T>).model;
  }
}