concept method in category flutter

appears as: method, method, methods, The method, The methods, methods
Flutter in Action

This is an excerpt from Manning's book Flutter in Action.

Listing 1.1. Example build method for the custom QuantityCounter stateful widget
Widget build(BuildContext context) {
  return Container(                         #1
    child: Row(
      children: List<Widget>[
         IconButton(
          icon: Icons.subtract,
          onPressed: () {                   #2
            setState(() {                   #3
               this.quantity--;
            });
          }),
        new Text("Qty: ${this.quantity}),   #4
        new IconButton(
          icon: Icons.add,
          onPressed: () {                   #5
            setState(() {
              this.quantity++;
            });
          }),
      ],
    )
  );
}

Flutter provides methods on the state object that allow you to respond to changes in the element tree. These methods are called in a specific sequence. This sequence is generally referred to as the widget’s lifecycle.

8.2.2. The inheritFromWidgetOfExactType and of methods

If you want to get information from an inherited widget down your widget tree, you’ll likely provide a reference to that inherited widget with a method called of. This method looks up the tree and finds the closest parent inherited widget of that type. For example, when you call Theme.of(BuildContext).primaryColor, Flutter is looking up the tree for the nearest Theme widget, as in figure 8.5, and grabbing the primaryColor property from it.

Figure 8.5. Using an InheritedWidget, you can grab references to widgets higher in the tree with the of method.

The of method is a Flutter convention, not something you get out of the box. Most of methods are defined on the inherited widgets themselves, and they usually turn around and call BuildContext.inheritFromWidgetOfExactType with the BuildContext you provide. inheritFromWidgetOfExactType is the actual method that looks up the tree, and it relies on the BuildContext to access the tree and look at its ancestors.

Because this method is static, it can be called from anywhere, without any reference to an instance of the class. The of method is really the secret to the inherited widget.

Listing 8.2. Custom of method
// e_commerce/lib/blocs/app_state.dart -- line ~13
class AppStateContainer extends StatefulWidget {
  final Widget child;
  final BlocProvider blocProvider;
  const AppStateContainer({
    Key key,
    @required this.child,
    @required this.blocProvider,
  }) : super(key: key);
 
  @override
  State<StatefulWidget> createState() => AppState();
 
  static AppState of(BuildContext context) {                         #1
    return (context.inheritFromWidgetOfExactType(_AppStoreContainer)
        as _AppStoreContainer).appData;                              #2
  }
}