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;
}
}
2
Answers
Dart null-safety. You can use
late
keyword.But for same name better practice will be
More about null-safety.
You can use an initializer list to initialize final variables outside the constructor like this:
But for this example you really should just write it as
This is more idiomatic, more concise. There’s no reason to write it the other way.