The above code is as if we got the spaceship object first (var s = getSpaceship()) and then extracted the fields (var name = s.name; var country = s.country;). Except by using records, we’re not polluting our local namespace with s.
To be honest, I haven’t been using this class restructuring syntax in my code so far. But maybe it’s because I tend to forget that the feature is there.
What other cool uses do you have for records? Or maybe there are uses of records that you learned to avoid?
Destructuring classes looks so unfamiliar! For me the fact that you wrap a record with Spaceship() as if this was a constructor suggest that a new Spaceship class gets created. It’s definitely cool feature, but quite confusing if you don’t know the syntax.
Using records with switch statements when evaluating multiple conditions:
void main() {
print(getMessage(canPrint: true, canEdit: true));
print(getMessage(canPrint: true, canEdit: false));
print(getMessage(canPrint: false, canEdit: true));
print(getMessage(canPrint: false, canEdit: false));
}
String getMessage({required bool canPrint, required bool canEdit}) {
return switch ((canPrint, canEdit)) {
(true, true) => 'You can print and edit',
(true, false) => 'You can print, but cannot edit',
(false, true) => 'You cannot print, but can edit',
(false, false) => 'You cannot print nor edit',
} +
' the document.';
}
Output:
You can print and edit the document.
You can print, but cannot edit the document.
You cannot print, but can edit the document.
You cannot print nor edit the document.
Nothing in the IDE tells you what you’re working with, not the buggy insertion of type that disappear nor the hover than can not link to declaration.
It also mean no source navigation.
I used them with parsimony and prototyping but often and quickly I move to classes.
I’ve badly used them as configurator objects or function returns but have replaced when consolidating.
I mostly use Dart records to return multiple objects from functions. I wrote a blog post about it. I like that you can use named fields so that you are always aware of what the function is returning.
Just keep in mind that if I define typedef RandalRecord = (String first, int second); they are completely interchangeable, unlike when you define proper Data classes, similar to how typedef X = String; doesn’t create a new type of string… it just aliases them together.
Flutter and the related logo are trademarks of Google LLC. We are not endorsed by or affiliated with Google LLC.
Using contents of this forum for the purposes of training proprietary AI models is forbidden. Only if your AI model is free & open source, go ahead and scrape.