Classes and objects

Dart is an object-oriented programming language, and objects and classes are important parts of what you'll be creating in Dart and Flutter. If you are not familiar with OOP concepts, I suggest reading an excellent article at the following address: https://medium.freecodecamp.org/object-oriented-programming-concepts-21bb035f7260.

Here, we'll have a quick overview of creating classes and objects in Dart. Let's begin by creating a Person class with two fields, name and surname:

class Person { 
String name;
String surname;
}

 

You can create instances of the Person class from the main method, and set the name and surname as follows:

main() { 
Person clark = Person();
clark.name = 'Clark';
clark.surname = 'Kent';
print ('${clark.name} ${clark.surname}');

}

There are a couple of interesting features in this code that are worth noting. Name and surname are both accessible from outside the class, but in Dart, there are no identifiers such as Private or Public. So, each property of a class is considered public unless its name begins with an underscore character (_). In this case, it becomes inaccessible from outside its library (or file).

In the Person clark = Person(); line, you are creating an instance of a Person() class, and the resulting object is contained in the clark variable. In Dart, you don't need to explicitly specify the new keyword, as it is implied. So writing Person clark = new Person(); would be exactly the same.

You'll find the omission of the new keyword extremely common with Dart developers, especially when developing in the Flutter framework.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.49.247