Flutter - Classes & Constructors

Table of Contents

Classes & Constructors

class Person {
  final String first;
  final String last;
  final String email;

  Person : first = "none"; // initializer list  assigns variables before the constructor runs
  
  Person(n) : first = n { print(n) } // Initializer with constructor (note {} replaces the ;)

  Person(this.first) // automatic assignment to instance var in constructor
  
  Person({this.first}) // curly braces make the value optional
  
  Person.myName(this.first) // Named constructors provide extra clarity and are needed for multiple contstructors



  //example - Named constructor taking a general map and email
  Person.fromMap(Map<String, dynamic> map, {this.email}) 
      : assert(map['first'] != null),
        assert(map['last'] != null),
        first = map['first'],
        last = map['last'];
 

}

More details in this good article

[[../../../_notes/_tech/Flutter/Flutter|Back to Flutter]]

References