Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I inherit static methods in dart/flutter?

Is it possible in Dart/Flutter to inherit static methods or factories? Or do I need to workaround this by creating an instance to access that static method?

My case is that I want to serialize an object but need to access a general parse function for them.

abstract class Foo {

  static Foo parse(); //Error, must have a body

  Foo parse();//No error but need to call Foo().parse(); by creating an instance.
}

I want to create by using json so is bad practice and against performance to create a new instance to return another one?

class InheritedFoo {

  final String string;

  InheritedFoo(this.string);

  @override
  Foo parse() {
    return InheritedFoo("some string");
  }
}

Is it maybe possible to use a singleton to save performance (call InheritedFoo.inst.parse() )?

like image 594
Paul Avatar asked Sep 06 '25 03:09

Paul


1 Answers

No you cannot do that. This excerpt is from the official Dart language specification:

enter image description here

like image 58
Vandad Nahavandipoor Avatar answered Sep 09 '25 17:09

Vandad Nahavandipoor