4

I was going through Firebase for flutter docs and found this line,i have no idea why ":" this symbol is used,I'm new to dart

 Record.fromMap(Map<String, dynamic> map, {this.reference})
     : assert(map['name'] != null),
       assert(map['votes'] != null),
       name = map['name'],
       votes = map['votes'];

and why am i not able to initialize like this

Record.fromMap(Map<String, dynamic> map, {this.reference}) {
  name = map['name'],
  votes = map['votes'];
}

link to the codelab https://codelabs.developers.google.com/codelabs/flutter-firebase/#4

and what does assert function do?

creativecreatorormaybenot
  • 114,516
  • 58
  • 291
  • 402
Chandru
  • 467
  • 1
  • 8
  • 17
  • You cannot intialize `final` members in a constructor because a constructor body is just another method that is called with the constructor parameters, which can call any non-static method in the class. This means that the member would not be `final` anymore because it would be changed at a later point. For the rest you can see the question that already has answers to your questions (marked it as duplicate). – creativecreatorormaybenot Dec 29 '19 at 13:05

1 Answers1

2

It's called Initializer list and it's the first thing that's called when invoking the constructor.

from the docs

Initializer list

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)');
}

Warning: The right-hand side of an initializer does not have access to this.

During development, you can validate inputs by using assert in the initializer list.

Point.withAssert(this.x, this.y) : assert(x >= 0) {
  print('In Point.withAssert(): ($x, $y)');
}

Initializer lists are handy when setting up final fields. The following example initializes three final fields in an initializer list. Click Run to execute the code.

class Point {
  final num x;
  final num y;
  final num distanceFromOrigin;

  Point(x, y)
      : x = x,
        y = y,
        distanceFromOrigin = sqrt(x * x + y * y);
}

Redirecting constructors

Sometimes a constructor’s only purpose is to redirect to another constructor in the same class. A redirecting constructor’s body is empty, with the constructor call appearing after a colon (:).

class Point {
  num x, y;

  // The main constructor for this class.
  Point(this.x, this.y);

  // Delegates to the main constructor.
  Point.alongXAxis(num x) : this(x, 0);
}
humazed
  • 74,687
  • 32
  • 99
  • 138