By Alvin Alexander. Last updated: March 16, 2022
I’m generally getting out of the writing business, but that being said, I don’t mind sharing some code as I go along. In this case I created the follow Dart programming examples as I reload Dart into my brain:
- Dart Factory pattern/method example
- Dart constructors with public and private fields
- Dart mixin example
Dart Factory example
First, here’s a simple Dart Factory pattern/method example:
abstract class Dog {
void speak();
factory Dog.createDog(DogType dogType) {
if (dogType == DogType.Small) {
return Poodle();
} else {
return Rottweiler();
}
}
}
class Poodle implements Dog {
void speak() => print('Imma Poodle');
}
class Rottweiler implements Dog {
void speak() => print('Imma Rottweiler');
}
enum DogType {
Small,
Large
}
void main() {
Dog d = Dog.createDog(DogType.Large);
d.speak();
}
That example can be improved, but for today it’s an okay start.
Dart constructor examples and private fields
Next, here’s an example of Dart constructors and public and private fields:
// dart fields are public by default
class Person {
String firstName;
String lastName;
Person(this.firstName, this.lastName);
}
// fields are private, so you need to define getters
// and setters when you want them
class PrivatePerson {
String _firstName;
String _lastName;
PrivatePerson(this._firstName, this._lastName);
// getters
String get firstName => _firstName;
String get lastName => _lastName;
// setters
void set firstName(String s) => _firstName = s;
void set lastName(String s) => _lastName = s;
}
void main() {
final p = Person('Alexander', 'Chigliak');
p.firstName = 'Alex';
p.lastName = 'Chiggy';
print(p.firstName);
print(p.lastName);
final pp = PrivatePerson('Alexander', 'Chigliak');
pp.firstName = 'Alvin';
pp.lastName = 'Alexander';
print(pp.firstName);
print(pp.lastName);
}
A Dart mixin example
Finally, here’s a Dart mixin example. It’s a partial conversion of a Scala example I share in the Scala Cookbook:
// can make this 'class' or 'mixin'
mixin HasTail {
void wagTail() => print("Tail is wagging");
void stopTail() => print("Tail is stopped");
}
abstract class Pet {
void speak() => print("Yo");
void comeToMaster();
}
class Dog extends Pet with HasTail {
void comeToMaster() => print("Woo-hoo, I'm coming!");
}
class Cat extends Pet with HasTail {
void comeToMaster() => print("That’s not gonna happen.");
void speak() => print("meow");
}
void main() {
Dog dog = Dog();
dog.speak();
dog.comeToMaster();
final cat = Cat();
cat.speak();
cat.comeToMaster();
}
In summary, if you needed some Dart programming examples, I hope those are helpful.