thumbnail

Introduction to Classes in Dart

Published on 29 March 2020
Last Updated on 29 March 2020

Dart is an object oriented programming language that supports inheritance via classes and mixins.

Every object in Dart is an instance of a Class and all classes descend from Object.

Classes in Dart are used for encapsulating data types, it is also used as a skeleton for building complex data types.

Dart has first class support Classes.

Classes in Dart can be used for implementing various functionalities. Once a Class is defined, various objects can be created from the same class by creating an Instance of the class.

Basic syntax of a Class

A class in Dart can be defined using following syntax:

class AnyDesiredClassName {
  // Default constructor or parameterized constructor
  // Named constructors
  // Factory constructors
  // Fields
  // Getters and setters
  // Methods
}

As shown above, a class name is defined after class keyword.

Class definition can include the following things:

  • Default Constructor or parameterized constructor
  • Named Constructor
  • Factory Constructor
  • Class Fields
  • Getters And Setters
  • Methods

etc.

Above things are explained in-depth in other chapters.

Example of a simple Class in Dart

Given below is a simple program using Dart classes, that demonstrates how classes can be used.

// a sample Car class
class Car {
  // default constructor
  Car(
    this.modelName,
    this.numOfWheels,
    this.price,
  );

  // fields
  final String modelName;
  final int numOfWheels;
  final double price;

  // class methods
  void printCarInfo() {
    print('''
car model is: ${modelName}    
number of wheels: ${numOfWheels}
price is: ${price}
    ''');
  }
}

main(List<String> args) {
  var car = new Car('Supra', 4, 2000);
  car.printCarInfo();
}

Above program produces following output:

car model is: Supra
number of wheels: 4
price is: 2000.0