Using context outside of build method in stateless widget

Viewed 312

I want to achieve multiple goals while implementing a widget:

  1. Using stateless widget
  2. Using theme for styling the widget
  3. Avoiding calling another method inside the build method - for performance reasons (i.e. avoiding initialising the same methods on every build)

lets take this widget for example:

class SomeWidget extends StatelessWidget {
  ButtonStyle _getStyle(context) {
    return ElevatedButton.styleFrom(primary: Theme.of(context).primaryColor);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        child: ElevatedButton(
            style: _getStyle(context),
            onPressed: () => ({}),
            child: Text("test")));
  }
}

the function _getStyle will be initialised on every build call, now while it looks not so bad as it is only small method - I consider it a bad practice.
but I dont have a way to get context outside of the build method (and I still want to use the global ThemeData)

if there was some flutter mechanism to prevent the _getStyle method to run multiple time through the widget life span - it could also be a solution. (i.e. like watch in vue.js)

How would you flutter experts out there suggest to approach this?

0 Answers
Related