Dart OOPs Concept.
Dart

Dart OOPs Concept

Hey everyone, welcome to our new article! Today, we’ll Dart OOPs Concept. Let’s get started!

Dart classes

Classes are like architectural blueprints that tell the system how to make an object, where an object is the actual data that’s stored in the computer’s memory. If a class is the blueprint, then you could say the object is like the house that the blueprint represents. For example, the String class describes its data as ac collection of UTF-16 code units, but a String object is something concrete like ‘Hello, Dart!’.

All values in Dart are objects that are built from a class. This includes the values of basic of basic types like int, double and bool.

That’s different from other languages like Java, where basic types are primitive. For example, if you have x = 10 in Java, the value of x is 10 itself. However, Dart doesn’t have primitive types. Even for a simple int, the value is an object that wraps the integer. You’ll learn more on this concept later.

Classes are a core component of object-oriented programming. They’re used to combine data and functions inside a single structure.

Dart OOPs Concept

The functions exist to transform the data. Functions inside of a class are known as methods, while constructors are special methods you use to create objects from the class.

It’s time to get your hands dirty. Working with classes is far more instructive than reading about them!.

Defining a class

To get started creating your own types, you’ll make a simple User class that has id and name properties. This is just the kind of class that you’re highly likely to create in the future for an app that requires user to log in.

Write the following simple class at the top level of your Dart file. Your class should be outside of the main function, either above or below it.

Dart OOPs Concept

This creates a class named User. It has two properties; id is an int with a default value of 0, and name is a String with the default value of an empty string.

Depending on the situation, null may be a better default than 0 or ” “.

Note:

Creating an object from a class

As mentioned above, the value you create from a class is called an object. Another name for an object is instance, so creating an object is sometimes called instantiating a class.

Since coding the class in your Dart file as you did above simply creates the blueprint, a User object doesn’t exits yet.
You can create one by calling the class name as you would call a function. Add the following line inside the main function:

Dart OOPs Concept

This creates an instance of your User class and stores that instance, or object, in user. Notice the empty parentheses after User. It looks like you’re calling a function without any parameters. In fact, you are calling a type of function called a constructor method.

The optional keyword new

Before version 2.0 of Dart came out, you had to use the new keyword to create an object from a class. At that time, creating a new instance of a class would have looked like this:

Dart OOPs Concept

In fact, this still works, but the new keyword is completely optional now, so it’s better to just leave it off. Why clutter your code with unnecessary word, right?

You’ll still come across new from time to time in the documentation or in legacy code, but at least now you won’t be confused by it. You can delete it if you come across it.

Assigning values to properties

Now that you have an instance of User stores in user, you can assign new values to this object’s properties by using dot notation. To access the name property, type user dot name, and then give it a value:

Dart OOPs Concept

Your code should look like the following:

Dart OOPs Concept

You’ll notice that you have both a function and a class together. Dart allows you to put multiple classes, top-level functions and even top-level variables all together in the same file.

You’ve defined a User data type with a class, created an object from it and assigned values to its parameters. Run the code now, though, and you won’t see anything special happen.
Now let see how to display data from an object.

Printing an object

You can print any object in Dart. However, if you try to print user now, you won’t get quite what you hoped for Add the following line at the bottom of the main function and run the code.

Dart OOPs Concept

Here’s what you get:

Instance of 'User'

Hmm, you were likely expecting something about Ray and the ID. What gives?

All classes in Dart are derived from Object, which has a toString. In this case, your object doesn’t tell Dart how to write its internal data when you call toString on it, so Dart gives you this generic, default output instead. However, you can override the Object class’s version of toString by writing you own implementation of toString, and thus customize how your own object will print out.

And the following method to the User class:

Dart OOPs Concept

Words that start with @ are called annotations. Including them is optional and doesn’t change how the code executes.
However, annotations do give the compiler more information so that it can help you out at compile time. Here, the @override annotation is telling both you and the compiler that toString is a method in Object that you want to override with your own customized version, so if you accidentally wrote the toString method signature incorrectly, the compiler would warn you about it because of the @override annotation.

Since methods have access to the class properties, you simply use that data to output a more meaningful messages when someone prints your object. Run the code now, and you’ll see the following result:

User(id 69, name: Tony Stark)

That’s far more useful!

Your User class only has a single method right now, but in classes with many methods, most programmers put the toString methods at or near the bottom of the class instead of burying it in the middle somewhere. As you continue to add to User, keep toString at the bottom. Following conventions like this makes navigating and reading the code easier.

Note:

Adding methods

Now that you’ve learned to override methods, you’re going to move on and add your own methods to the User class. But before you do, there’s a little background information that you should know.

Object Serialization

Being able to organize related data into a class super useful, especially when you want to pass that data around as a unit within your app. One disadvantage, though, shows up when you’re saving the object or sending it over the network.

Files, databases and networks only know how to handle simple data types, such as numbers and strings. They don’ know how to handle anything more complex like your User data type.

Serialization

Serialization is the process of converting a complex data object into a string. Once the object has been serialized, it’s easy to save that data or transfer it across the network because everything from you app to the network and beyond knows how to deal with strings. Later, when you want to read that data back in, you can do so by way of deserialization, which is simply the process of converting a string back into an object of your data type.

You didn’t realize it, but you actually serialized your User object in the toString method above. The code you wrote was good enough to get the job done, but you didn’t really follow any standardized format. You simply wrote it out in a way that looked nice to the human eye. If you gave that string to someone else, though, they might have some difficulty understanding how to deserialize it, that is, convert it back into a User object.

It turns out that serialization and deserialization are such common tasks that people have devised a number of standardized formats for serializing dat. One of the most common is called JSON: JavaScript Object Notation. Despite the name, it’s used far and wide outside the world of JavaScript.

Adding a JSON serialization method

You’re going to add another method to your class now that will convert a User object to JSON format. It’ll be similar to what you did in toString.

Add the following method to the User class, putting it above the toString method:

Dart OOPs Concept

Here are a few things to note:

  • Since this is your own custom method and you’re not overriding a method that belongs to another class, you don’t add the @overide annotation.
  • In Dart naming convention, acronyms are treated as words. Thus, toJson is better name than toJSON.
  • There’s nothing magic about serialization in this case. You simply used string interpolation to insert the property values in the correct locations in the JSON formatted string.
  • In JSON, objects are surrounded by curly braces, properties are separated by commas, property names are separated from property values by colons, and strings are surrounded by double-quotes. If a string needs to include a double-quote inside itself, you escape it with a backslash like so: \”.
  • JSON is very similar to a Dart data type called Map. In fact, Dart even has built-in functions in the dart:convert library to serialize and deserialize JSON maps. And that’s actually what most people use to serialize objects.
Dart OOPs Concept

To test out your new function, add the following line to the bottom of the main method:

print(user.toJSON());

This code calls the custom toJSON method on your user object using dot notation. The dot goes between the object name and method name just like you saw earlier for accessing a property name.

Run the code and you’ll see the following:

{"id": "69", "name" "Tony Stark"}

It’s very similar to what toString gave you, but this time it’s in standard JSON format, so a computer on the other side of the world could easily convert that back into a Dart object.

Cascade notation

When you created your User object above, you set its parameters like so:

Dart OOPs Concept

However, Dart offers a cascade operator (..) that allows you to chain together multiple assignments on the same object without having to repeat the object name. The following code is equivalent:

Dart OOPs Concept

Note that the semicolon only appears on the last line.

Cascade notation isn’t strictly necessary, but it does makes your code just a little tidier when you have to assign a long list of properties or repeatedly call a method that modifies your object.

Check out more articles related to Dart Tutorial:

Switch Statement in Dart

Control Flow in Dart

String in Dart

Type Inference Variable in Dart | Dart Tutorial #2

Dart Tutorial is for Beginners from Scratch #1

One thought on “Dart OOPs Concept

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top