Define Dart Class
Define Dart Class
In this tutorial, we will learn how to define a Dart class using the class keyword. The class keyword is followed by the user-defined class name, which is provided inside the curly braces. A Dart class can consist of fields, constructors, getters, setters, and methods.
Syntax
The general syntax of the Dart class is as follows:
class class_name {
<fields>
<getters/setters>
<constructor>
<methods>
}
Example
/*
Define a Dart class
Dart Tutorials – www.TestingDocs.com
*/
void main() {
var book =new Book();
book.title=”The Old man and the Sea”;
book.author=”Ernest Hemingway”;
book.pages=98;
book.price=90;
//Accessing class Function
book.displayBookInfo();
}
//Define a class Book
class Book {
var title;
var author;
var pages;
var price;
// Class Function
displayBookInfo() {
print(“Book Name is : ${title}”);
print(“Book Author is :${author}”);
print(“Number of Pages: ${pages}”);
print(“Book Price is: ${price}”);
}
}
Explanation
In this example, we have declared a class called Book. The Book class has the following fields
title
author
pages
price
The displayBookInfo() is a class function that prints the fields of the Book class.
—
Dart Tutorials
Dart tutorial on this website can be found at:
https://www.testingdocs.com/dart-tutorials-for-beginners/