skip to Main Content

I have a class (let’s say a Flutter stateless widget), which has a helper method inside:

class MyWidget extends StatelessWidget {
  const MyWidget();

  // static?
  Foo _helper() {
    // ... Other instructions that don't need `this`.
    // Ex:
    final now = DateTime.now();
    // ...
  }

  @override
  Widget build(BuildContext context) {
    final foo = _helper();
    // ...
  }
}

This method could be static as it doesn’t need to access the instance.
It would work as a static method and it would work as a non-static method too.
Having seen this question, I was wondering what was the best practice in this scenario.

2

Answers


  1. Methods don’t matter as much as fields.

    Static methods are better to be used, and they can also be called from other classes, without the need to create an instance (to access an instance method). They can also be copied as-is to other classes without much effort.

    The drawback is that the a static method doesn’t have access to instance fields or methods.

    Fields are another thing, because static ones live for the lifetime of the program, so they should be used with care.

    Login or Signup to reply.
  2. In general, use whatever makes the most sense conceptually for your API. Choosing to use static affects your API because, unlike some other languages, Dart does not provide syntactic sugar to allow static methods to be invoked as instance methods. (That is, you must invoke static methods as SomeClass.someStaticMethod() and cannot do SomeClass().someStaticMethod().

    Another consideration is whether you want your method to be possibly overridden by derived classes. static methods aren’t involved with polymorphism.

    Neither of those apply to your case where your method is private and therefore free of public API considerations and from being overridden. In that case, I would use a static method since it should be more efficient to invoke; "static" means that it is resolvable at compile-time and does not involve any runtime virtual dispatch.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search