OneBite.Dev - Coding blog in a bite size

Declare An Object In Dart

Code snippet for how to Declare An Object In Dart with sample and detail explanation

Object-oriented programming (OOP) represents a fundamental concept in various programming languages, including Dart. This article aims to exhibit how to declare an object in Dart effectively and intending to provide a comprehensive understanding.

Code Snippet for Object Declaration

In Dart, before we can create objects, we need to define classes. A class is a blueprint for an object. Once we have a class, we can create an instance of the class, which is an object. Here is a simple example of declaring an Object in Dart:

class Student {  
  var studID;  
  var studName;  
  
  showStudInfo(){  
    print(studID); 
    print(studName);  
  }  
}

void main() {  
  var student1 = new Student();   // Creating Instance of student  
  student1.studID = 1001;         // Setting up studID
  student1.studName = "Amy";      // Setting up studName
  student1.showStudInfo();  
}

Code Explanation for Object Declaration

Let’s break down the previous Dart code snippet to understand more:

  1. We first declare a class named Student with properties: studID and studName. This class also has a showStudInfo function that prints out the student’s ID and name.

  2. In the main() function, we create an instance of Student class called student1. The new keyword is being used before the Student constructor to create a new object from the class.

  3. After creating the student1 object, we assign values to studID and studName properties using the dot . operator. It is worth noting that property values are not fixed and can be changed by the object’s user.

  4. Finally, we call the function showStudInfo() for the student1 object. Again, the dot . operator is used to call this function. This function will print the values of studID and studName.

In conclusion, an object in Dart is declared by first defining the class and then creating an instance of the class. The instance, in this case, is student1, and the class is Student. Through the instance, we can access and manipulate the properties and functions defined in that class.

dart