Kotlin `apply()` method analog in Dart
752
While there is no exact analog I stumbled upon a peculiar operator called Cascade notation that does similar job.
The given example will look something like:
UserDetails userDetails = userRepo.getUser()
..name = 'Name'
..email = '[email protected]'
..callSomeInnerMethodOfUserDetails();
You can also do a nested cascade also
UserDetails otherUserDetails = userRepo.getUser()
..name = (userRepo.getUser()
..firstName= "Other Name"
..assignFirstNameAndSurnameToNameField()).name
..email = "otherEmail"
..callSomeInnerMethodOfUserDetails();
Hope it helps.
Author by
Pavlo Ostasha
Updated on December 20, 2022Comments
-
Pavlo Ostasha over 1 year
I would like to be able to do something like
apply()
from Kotlin in Dart. For example in Kotlinvar userDetails: UserDetails = userRepo.getUser().apply{ //here 'this' is UserDetails so all the further calls are made in that context name = "Name" email = "[email protected]" callSomeInnerMethodOfUserDetails() };
Is there some similar method or way to do it in Dart language?
I want to know whether there are some things in standard library or language itself, rather than my own generic closure extension for such a purpose?
Thanks.