Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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