• Guides
    • Getting started with Dart
  • Blog
  • FAQ
    • Dart
    • Flutter
  • Contact
  • Guides
    • Getting started with Dart
  • Blog
  • FAQ
    • Dart
    • Flutter
  • Contact
  • Getting Started with Dart
    • Dart Variables
    • Dart Operators
    • Dart Comments
  • Dart Data Types
    • Dart Strings
    • Dart Numbers
    • Dart Booleans
    • Dart Lists
    • Dart Maps
  • Control Flow
    • Dart if...else Statements
    • Dart switch Statement
    • Dart for Loop
    • Dart for...in Loop
    • Dart while and do...while Loops
    • break and continue Statements
  • Dart Functions
  • Dart Classes
  • Dart Objects
  • Dart Constructors
  • Dart Exceptions

Dart Objects

210 views 0

Written by Ajaya Shrestha
January 20, 2022

In this chapter, we will learn about the dart objects and how they are used with the help of examples.


Dart Object

In the previous chapter, we learned about the dart classes. A class is a blueprint for an object. A class consists of data for the object. We can create an object from a class.

For example,

class Car {  
   // field 
   String color = "black";  
   
   // function 
   void screen() { 
      print(color); 
   } 
}

In the above example, Car is the class.

Now we can create multiple objects from the above class.


Create an Object

To create dart object from the class, we use the new keyword followed by the class name.

The syntax for creating an object is:

var object_name = new class_name();

The object_name refers to the name of the object.

The new keyword instantiates the class.

For example,

var obj1 = new Car("Model");

Example of an Object

class Car {
    String name = 'car_name';
    String color = 'car_color';
    
    void screen() { 
      print(color + ' ' + name); 
   }
}

void main() {
    var tesla = new Car();
    tesla.name = 'Tesla';
    tesla.color = 'Red';

    print(tesla);
    print(tesla.name);
    print(tesla.color);
    tesla.screen();
}

Output

Instance of 'Car'
Tesla
Red
Red Tesla

In the above example, Car is a class and tesla is an object.

We can access the fields and methods of a class using the dot notation.

Was this helpful?

Yes  No
Related Articles
  • Dart Constructors
  • Dart Exceptions
  • Dart Classes
  • Control Flow
  • Dart Functions
  • break and continue Statements
Previously
Dart Classes
Up Next
Dart Constructors
flutter-dev-experts




FLUTTERGUIDE
FlutterGuide is an easy learning guide platform to help you build apps for any screen. The leading Dart/Flutter guides for getting started and become pro.
Guides
  • Getting started with Dart 22
  • Private Documentation 1
Categories
  • Firebase
  • Dart
  • iOS
  • API
  • Bloc
  • Flutter
  • Widgets
  • Mobile
  • State Management
  • Design
  • Animations
  • Flutter Designs
About
About Us
Guides
Blogs
FAQs
Contact
  • Privacy Policy
  • Terms & Conditions
  • Copyright 2022 Fawesome Apps. All Rights Reserved