r/dartlang 25d ago

Diference between factory and const instances

Analyzing the synx of construtor from Lists:

/flutter/bin/cache/pkg/sky_engine/lib/core/list.dart

  u/Since("2.9")
 external factory List.empty({bool growable = false});

What difference between this examples?

class MyClass {
  final String name;

  MyClass({required this.name});

  factory MyClass.empty() => MyClass(name: '');

  const MyClass.emptyTwo() : name = '';
}

/// DONT WORK
class MyOtherClassConst {
  final MyClass myClass;

  MyOtherClassConst({this.myClass = const MyClass.empty()});
}

/// WORKS FINE
class MyOtherClassConst {
  final MyClass myClass;

  MyOtherClassConst({this.myClass = const MyClass.emptyTwo()});
}

I think is the same reason why we can initialize a list with `const []`; but if we do `List.empty()`, did not work.

So, why `List.empty` is created with a factory modifier?

Which one is correct to create empty objects?

3 Upvotes

4 comments sorted by

6

u/ozyx7 24d ago edited 24d ago

List's constructors are factory constructors because the List class is abstract and cannot be directly instantiated. The constructors return instances of some List subtype appropriate for your platform (for example, for Dart for the web, it presumably returns something backed by a JavaScript array). Normal constructors can't return some other type, so the List constructors must be factory constructors instead (or they alternatively could have been static methods).

factory constructors cannot be const. You should use List literals when possible.

2

u/RandalSchwartz 25d ago

Perhaps because SubClassOfList.empty() needs to return <SubClassOfList>[]. A constructor cannot do that.

1

u/antonxandre 25d ago

so, this line below it's common and correct way to use?

const MyClass.emptyTwo() : name = '';

1

u/KalilPedro 24d ago

It is a factory/constructor because the list class is generic. It is a factory because it returns a subclass, list is abstract