Programming in Dart: Classes

Jun 28 2022 · Dart 2.17, Flutter 3.0, DartPad

Part 1: Understand Classes

04. Write a Constructor

Episode complete

Play next episode

Next
About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 03. Challenge: Create a Custom Class Next episode: 05. Challenge: Define a Constructor

Get immediate access to this and 4,000+ other videos and books.

Take your career further with a Kodeco Personal Plan. With unlimited access to over 40+ books and 4,000+ professional videos in a single subscription, it's simply the best investment you can make in your development career.

Learn more Already a subscriber? Sign in.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

So far, we’ve been creating objects and then setting up values after the fact. This can lead to cases where you might operate on an object before setting it. Now you can promise yourself to be vigilant, but you’re just setting yourself up for an error. Thankfully, we can use a constructor.

class User {
  int id = 0;
  String name = '';
}
var user = User()
..name = 'Ray'
..id = 42;
User(int id, String name) {
    this.id = id;
    this.name = name;
}
User(int id, String name) {
    id = id;
    name = name;
}
var user = User(42, 'ray');
print(user.id);
User(int id, String name) {
    this.id = id;
    this.name = name;
}
User(this.id, this.name);
User(this.id, this.name) { 
    print('this space for rent');
}
var user2 = User();
class User {
  final int id;
  final String name;
  
  User(this.id, this.name);
  
}