Skip to content

Instantly share code, notes, and snippets.

@erluxman
Last active April 8, 2020 02:02
Show Gist options
  • Save erluxman/290e17306b745ed83b9242653ca55041 to your computer and use it in GitHub Desktop.
Save erluxman/290e17306b745ed83b9242653ca55041 to your computer and use it in GitHub Desktop.
Method / variable call chaining in dart.
//Cascade/Chaining/Fluent Operations
//We can chain method/member calls without returning `this` from method/getter/setter
class User {
String name;
int age;
User({this.name = "Foo", this.age = 0});
User withName(String name) {
this.name = name;
return this;
}
User withAge(int age) {
this.age = age;
return this;
}
void printId() => print("$name is $age years old.");
}
void main() {
withoutCascadeOperator();
withCascadeOperator();
}
withoutCascadeOperator() {
print("Without Cascade Operator".toUpperCase());
User user = User();
user.printId();
user
.withAge(27)
.withName("Laxman");
user.printId();
}
withCascadeOperator() {
print("\n-----------------------------------------\n"+
"With Cascade Operator".toUpperCase());
User user = User()
..age=27
..name="Laxman"
..printId();
user
..age= 30
..name="Ram";
user.printId();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment