class class_name {
//rest of the code here:
}
class Car {
// field
String engine = "E1001";
// function
void disp() {
print(engine);
}
}
class Spacecraft {
String name;
DateTime? launchDate;
// Read-only non-final property
int? get launchYear => launchDate?.year;
// Constructor, with syntactic sugar for assignment to members.
Spacecraft(this.name, this.launchDate) {
// Initialization code goes here.
}
// Named constructor that forwards to the default one.
Spacecraft.unlaunched(String name) : this(name, null);
// Method.
void describe() {
print('Spacecraft: $name');
// Type promotion doesn't work on getters.
var launchDate = this.launchDate;
if (launchDate != null) {
int years = DateTime.now().difference(launchDate).inDays ~/ 365;
print('Launched: $launchYear ($years years ago)');
} else {
print('Unlaunched');
}
}
}
// Class Declaration
class AClass {}
void main() {
// Object creation
var a = AClass();
// Access Object property
print(a.hashCode);
print(a.runtimeType);
// Access String Object method
print("vel".toUpperCase());
// Access int property
print(2.isNegative);
print(2.runtimeType);
}
Mixins are a way of reusing a class’s code in multiple class hierarchies.
To use a mixin, use the with keyword followed by one or more mixin names. The following example shows two classes that use mixins:
class MyClass with MyMixin {
// ···
}
To implement a mixin, create a class that extends Object and declares no constructors.
Unless you want your mixin to be usable as a regular class, use the mixin keyword instead of class.
For example:
mixin MyMixin {
// ···
}
class Person {
String name = 'Lara';
int age = 12;
Person({this.name = '', this.age = 18});
}
int addNumbers(int num1, int num2) {
return num1 + num2;
}
void main() {
var p1 = Person(name: 'Gabriel', age: 18);
var p2 = Person(name: 'Clara', age: 29);
print({'name': p1.name, 'age': p1.age});
print({'name': p2.name, 'age': p2.age});
}