Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set final/const properties in Dart constructor

Tags:

I have a class with an immutable property, int id. How do I pass the value of id to the constructor?

class Hey
{
  var val;
  final int id;
  Hey(int id,var val)
  {
    this.id=id;
    this.val=val;
  }
}

void main()
{
  Hey hey=new Hey(0,1);
}

hey.dart:10:10: Error: Setter not found: 'id'. this.id=id; ^^ hey.dart:10:10: Error: The setter 'id' isn't defined for the class 'Hey'. - 'Hey' is from 'hey.dart'. Try correcting the name to the name of an existing setter, or defining a setter or field named 'id'. this.id=id; ^^

I don't think a setter is required for a const or final field property. The API is not clear on how to handle this.

like image 657
Steve Strongheart Avatar asked Jun 22 '19 03:06

Steve Strongheart


People also ask

What is const constructor Dart?

A const constructor is an optimization! The compiler makes the object immutable, allocating the same portion of memory for all Text('Hi!') objects. But not Text(Math. random()) though, as its value can't be determined at compile time!

How do I set default value in constructor Dart?

Dart/Flutter Constructor default value For the constructors with either Named or Positional parameters, we can use = to define default values. The default values must be compile-time constants. If we don't provide value, the default value is null.


1 Answers

From the Dart language tour:

Note: Instance variables can be final but not const. Final instance variables must be initialized before the constructor body starts — at the variable declaration, by a constructor parameter, or in the constructor’s initializer list.

And the section on initializer lists says:

Besides invoking a superclass constructor, you can also initialize instance variables before the constructor body runs. Separate initializers with commas.

// Initializer list sets instance variables before
// the constructor body runs.
Point.fromJson(Map<String, num> json)
    : x = json['x'],
      y = json['y'] {
  print('In Point.fromJson(): ($x, $y)');
}

So the general way is through initialization lists.

As mentioned above, you also can initialize at variable declaration:

class Foo {
  final x = 42;
}

or can initialize them by a constructor parameter:

class Foo {
  final x;

  Foo(this.x);
}

although those other approaches might not always be applicable.

like image 67
jamesdlin Avatar answered Sep 27 '22 19:09

jamesdlin