Constructor in dart as compared in Swift

Coming from Swift this works well in Swift –

class Test {
    let userId: Int?
    let id: Int?
    let title: String?
    
    init(userId: Int, id: Int, title: String) {
        self.id = id
        self.title = title
        self.userId = userId
    }
    
}

Now while trying dart documentation I tried this , it works

class Album {
   int? userId;
  int? id;
  String? title;

    Album({required int userId, required int id, required String title}) {
     this.userId = userId;
     this.id = id;
     this.title = title;
   }
  
}

but if I were to add final keyword which is like let in swift it stops working and I have to do some thing like below –

class Album {
   final int? userId;
   final int? id;
    final String? title;

  
    const Album({required this.id, required this.userId, required this.title});
}

I have no idea why this works and why this below does not – is it just something I have to start doing or is there any logic behind it as well –

class Album {
   final int? userId;
   final int? id;
    final String? title;

    Album({required int userId, required int id, required String title}) {
     this.userId = userId;
     this.id = id;
     this.title = title;
   }
   
}

>Solution :

Dart null-safety. You can use late keyword.

class Album {
  late final int? userId;
  late final int? id;
  late final String? title;

  Album({required int userId, required int id, required String title}) {
    this.userId = userId;
    this.id = id;
    this.title = title;
  }
}

But for same name better practice will be

class Album {
  final int? userId;
  final int? id;
  final String? title;
  const Album({
    this.userId,
    this.id,
    this.title,
  });
}

More about null-safety.

Leave a Reply