Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 –

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading