flutterdartinherited-widget

Assigning InheritedWidget in build-Method


Let A be an InheritedWidget, that I can get throughout the whole app by calling A.of(context).

If I have a StatefulWidget, what is the better option (in terms of performance or code quality):

A)

class Test extends StatefulWidget {
  
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  
  A a;
  
  @override
  Widget build(BuildContext context) {
    a ??= A.of(context);
    return Container();
  }
}

B)

class Test extends StatefulWidget {
  
  @override
  _TestState createState() => _TestState();
}

class _TestState extends State<Test> {
  @override
  Widget build(BuildContext context) {
    final a = A.of(context);
    return Container();
  }
}

I have never seen someone using Option A), so I am wondering. I prefer Option A) because every method in the _TestState class can use the a-Object easily and it is also assigned only once in the build method.


Solution

  • Option B is likely enough if you keep widgets small. It won't be great if you have many methods that depend on the inherited widget.

    Reading option A brings up questions in my mind like

    Both options work though.

    In terms of code quality a third option is to apply the dependency inversion principle by making A a parameter to the widget.

    class MyStatefulWidget extends StatefulWidget {
      MyStatefulWidget({@required this.a});
      final A a;
      ...
    }
    
    

    Then callers can create it with MyStatefulWidget(a: A.of(context)). This reads better than option A, though, granted, they're not equivalent.

    I'm not aware of performance differences considerable enough to discuss here.