class Animal {
void makeSound() {
print('The animal makes a sound.');
}
}
class Dog extends Animal {
@override
void makeSound() {
print('The dog barks.');
}
}
class Cat extends Animal {
@override
void makeSound() {
print('The cat meows.');
}
}
void main() {
Animal animal = Animal();
Animal dog = Dog();
Animal cat = Cat();
animal.makeSound(); // Output: The animal makes a sound.
dog.makeSound(); // Output: The dog barks.
cat.makeSound(); // Output: The cat meows.
}​
In the example above, we have an `Animal
` superclass and two subclasses, `Dog
` and `Cat
`. Each subclass overrides the `makeSound()
` method inherited from the `Animal
` class with its own implementation.main()
` function, we create instances of `Animal
`, `Dog
`, and `Cat
` and assign them to variables of type `Animal
`. Despite the variables being of the `Animal
` type, the polymorphic behavior allows us to call the `makeSound()
` method on each object. The actual implementation of the method that gets executed depends on the type of the object. So, when we call `makeSound()
` on the `dog
` variable, the overridden `makeSound()
` method from the `Dog
` class is invoked, producing the output "The dog barks." abstract class Joker{
void makePeopleLaugh();
}
class Clown implements Joker{
void makePeopleLaugh() {
// Here is where the magic happens
}
}
class Comedian implements Joker{
void makePeopleLaugh() {
// Here is where the magic happens
}
}​
https://dart.dev/get-dart
) and follow the installation instructions for your specific operating system..dart
` extension.hello.dart
` and add the following code: void main() {
print('Hello, Dart!');
}​
cd
` command to navigate to the directory where your Dart file is located. For example, if your `hello.dart
` file is located in the `dart_projects
` folder on your desktop, you can use the following command: cd ~/Desktop/dart_projects​
5. Run the Dart application : In the command-line interface, use the `dart
` command followed by the name of your Dart file to run the application. For example, to run the `hello.dart
` file, use the following command: dart hello.dart​
Hello, Dart!​
is
" and "as
" keywords are used for type checks and type casts, respectively.is
" keyword is used for type checks to determine if an object is of a specific type. It returns a boolean value, true or false, based on the object's type. It is commonly used in conditional statements or to perform type-specific operations. var obj = 'Hello';
if (obj is String) {
print('The object is a String.');
} else {
print('The object is not a String.');
}​
is
" keyword is used to check if the variable `obj
` is of type String. If it is, the message "The object is a String." will be printed; otherwise, the message "The object is not a String." will be printed.as
" keyword is used for type casts, allowing you to explicitly cast an object to a specific type. It performs a type check at runtime and casts the object to the desired type if the check is successful. If the object cannot be cast to the specified type, a runtime exception may occur. var obj = 'Hello';
var str = obj as String;
print(str.toUpperCase());​
as
" keyword is used to cast the variable `obj
` to the String type and assign it to the variable `str
`. Since `obj
` is already a String, the cast is successful, and the `toUpperCase()
` method can be called on `str
`.TypeError
`, may occur. Therefore, it is recommended to use the "is
" keyword to perform a type check before using the "as
" keyword for type casting to ensure safety.is
" and "as
" keywords are useful when dealing with polymorphism, conditional branching based on object types, and when you need to perform specific operations based on an object's type in Dart. String name = 'John'; // A string variable
int age = 25; // An integer variable​
2. Dynamic Typing : var name = 'John'; // The type of 'name' is inferred as String
var age = 25; // The type of 'age' is inferred as int
var value = 3.14; // The type of 'value' is inferred as double​
@Deprecated
` annotation is used to mark code elements (such as classes, methods, fields, or parameters) as deprecated. It serves as a documentation tool to indicate that a particular element is no longer recommended for use and may be removed or replaced in future versions of the code or library.@Deprecated
`, it generates a warning or error at compile-time, notifying developers that they are using deprecated code. This helps prevent accidental usage of deprecated elements and encourages developers to migrate to alternative or updated code.@Deprecated
` annotation in Dart:class DeprecatedClass {
@Deprecated('This class is deprecated. Use NewClass instead.')
void deprecatedMethod() {
// Deprecated method implementation
}
}
void main() {
DeprecatedClass deprecatedInstance = DeprecatedClass();
deprecatedInstance.deprecatedMethod(); // Generates a warning or error
}​
In the example above, the `deprecatedMethod()
` in the `DeprecatedClass
` is marked as deprecated using the `@Deprecated
` annotation. The annotation includes an optional string parameter that provides a deprecation message explaining why the element is deprecated and suggests an alternative.deprecatedMethod()
` is called in the `main()
` function, it generates a warning or error depending on the configuration. The warning or error message will include the deprecation message specified in the `@Deprecated
` annotation, indicating that the method is deprecated and suggesting the use of an alternative.@Deprecated
` annotation effectively, developers can communicate the deprecation of certain code elements and provide guidance on how to migrate to newer or recommended alternatives. This helps maintain code quality, encourages codebase evolution, and informs other developers about potential changes in the API. void myFunction(int a, int b) {
// Function body
}​
void main() {
// Function Declaration
int result = myFunction(3, 4);
print(result); // Output: 7
// Function Expression
var myFunctionExpr = (int a, int b) => a * b;
int exprResult = myFunctionExpr(3, 4);
print(exprResult); // Output: 12
}
int myFunction(int a, int b) {
return a + b;
}​
myFunction
` using a function declaration, and another function `myFunctionExpr
` using a function expression. We call both functions and observe the output.myFunction
` is defined before it is used, and it adds two numbers. The function expression `myFunctionExpr
` is assigned to a variable and multiplies two numbers using the fat arrow notation. class Animal {
void eat() {
print('The animal is eating.');
}
}
class Dog extends Animal {
void bark() {
print('The dog is barking.');
}
}​
class A {
void methodA() {
print('Method A');
}
}
class B {
void methodB() {
print('Method B');
}
}
class C with A, B {
void methodC() {
print('Method C');
}
}​
3. Hierarchical inheritance : class Animal {
void eat() {
print('The animal is eating.');
}
}
class Dog extends Animal {
void bark() {
print('The dog is barking.');
}
}
class Cat extends Animal {
void meow() {
print('The cat is meowing.');
}
}​
1, 2, -5,
etc.3.14, -0.5,
etc.'
`) or double (`"
`) quotes.Hello, Dart!
'`, `"FreeTimeLearn
"`true
` or `false
`. They are useful for making decisions and controlling program flow.true
`, `false
`[1, 2, 3]
`, `['apple', 'banana', 'orange']
`
{'name': 'John', 'age': 25, 'country': 'USA'}
`{1, 2, 3, 4, 5}
`dynamic
` type represents a variable that can hold values of any type. The type is determined at runtime, allowing for flexibility but sacrificing some compile-time type checking.dynamic dynamicVar = 10;
`, `dynamicVar = 'Hello';
`var
` keyword allows Dart to infer the type of a variable based on its assigned value. It's a shorthand way of declaring a variable without explicitly specifying the type.var name = 'John';
`, `var count = 5;
`returnType functionName(parameter1, parameter2, ...) {
// Function body
// Code statements
// Optional return statement
}​
returnType
` represents the type of value that the function returns. It can be any valid Dart type, such as `void
`, `int
`, `String
`, etc. If the function does not return a value, the `void
` keyword is used.functionName
` is the identifier for the function. It should follow Dart naming conventions and describe the purpose or action performed by the function.int a, String b
`. You can also specify default values for parameters.{}
`. You write the necessary code statements to perform the desired operations or calculations within the function.return
` keyword followed by an expression to return a value from the function. The return statement is optional in void functions.
Here's an example of a simple function in Dart :int sum(int a, int b) {
int result = a + b;
return result;
}​
sum
` that takes two `int
` parameters (`a
` and `b
`). The function body calculates the sum of the parameters and stores it in the `result
` variable. Finally, the `result
` is returned using the `return
` statement.int total = sum(5, 3);
print(total); // Output: 8​
sum
`, and the arguments `5
` and `3
` are passed to the function. The returned value is stored in the `total
` variable and printed to the console.length
` property returns the number of characters in a string. String str = 'Hello, Dart!';
print(str.length); // Output: 13​
String str = 'Hello, Dart!';
print(str.toUpperCase()); // Output: HELLO, DART!
print(str.toLowerCase()); // Output: hello, dart!​
trim()
` method removes leading and trailing whitespace characters from a string. String str = ' Hello, Dart! ';
print(str.trim()); // Output: Hello, Dart!​
split()
` method splits a string into a list of substrings based on a specified delimiter. String str = 'apple,banana,orange';
List fruits = str.split(',');
print(fruits); // Output: [apple, banana, orange]​
substring()
` method returns a new string that is a substring of the original string, starting at a specified index and optionally ending at another index. String str = 'Hello, Dart!';
print(str.substring(7)); // Output: Dart!
print(str.substring(0, 5)); // Output: Hello​
6. indexOf() / lastIndexOf() : These methods return the index of the first/last occurrence of a specified substring within a string. If the substring is not found, they return -1. String str = 'Hello, Dart!';
print(str.indexOf('Dart')); // Output: 7
print(str.lastIndexOf('l')); // Output: 10​
String str = 'Hello, Dart!';
print(str.startsWith('Hello')); // Output: true
print(str.endsWith('!')); // Output: true​
contains()
` method checks if a string contains a specified substring, returning a boolean result. String str = 'Hello, Dart!';
print(str.contains('Dart')); // Output: true
print(str.contains('Python')); // Output: false​
replace()
` method replaces all occurrences of a specified substring with another substring. String str = 'Hello, Dart!';
String newStr = str.replaceFirst('Dart', 'World');
print(newStr); // Output: Hello, World!​
class Person {
String name;
int age;
// Constructor with parameters
Person(String name, int age) {
this.name = name;
this.age = age;
}
// Named constructor
Person.guest() {
name = 'Guest';
age = 18;
}
// Constructor with initialization list
Person.fromJson(Map<String, dynamic> json)
: name = json['name'],
age = json['age'];
// Regular function
void sayHello() {
print('Hello, my name is $name. I am $age years old.');
}
}
void main() {
// Creating objects using different constructors
Person person1 = Person('Alice', 25);
Person person2 = Person.guest();
Person person3 = Person.fromJson({'name': 'Bob', 'age': 30});
// Calling a regular function
person1.sayHello();
person2.sayHello();
person3.sayHello();
}​
Person
` class has multiple constructors. The first constructor takes `name
` and `age
` as parameters and initializes the instance variables. The second constructor named `guest
` sets default values for a guest user. The third constructor `fromJson
` takes a JSON map and initializes the object based on the provided data.returnType
functionName(parameters)
` syntax and can be called anywhere in the code.async
" and "await
" keywords are used in conjunction to handle asynchronous operations and make asynchronous code more readable and manageable. Here's an explanation of each keyword and their purpose:async
" keyword is used to mark a function as asynchronous. An asynchronous function can perform time-consuming operations without blocking the execution of other code. It allows you to write code that appears synchronous even though it may involve asynchronous tasks.async
," it means that the function can use the "await
" keyword to pause its execution and wait for asynchronous operations to complete. Asynchronous functions return a Future object that represents the eventual completion of the function's execution.await
" keyword is used within an asynchronous function to pause its execution until a Future completes and returns a result. It can only be used inside an "async" function. When an "await" expression is encountered, the function is temporarily suspended, allowing other code to execute.await
" keyword is typically used before an asynchronous operation, such as making an HTTP request, reading from a file, or querying a database. It allows you to write code that waits for the completion of the asynchronous task before proceeding.await
," you can write asynchronous code that looks and behaves more like synchronous code, making it easier to read, understand, and reason about asynchronous operations.async
" and "await
":import 'dart:io';
void main() async {
print('Start');
await performTask();
print('End');
}
Future<void> performTask() async {
print('Task started');
await Future.delayed(Duration(seconds: 2));
print('Task completed');
}​
In the example above, the `main
` function is marked as "async
," which allows it to use the "await
" keyword. Inside the `main
` function, we call the `performTask
` function using "await
," which suspends the execution of the `main
` function until the `performTask
` function completes.performTask
` function is also marked as "async" and returns a `Future<void>
`. Inside the `performTask
` function, we use `await
` before `Future.delayed
` to pause the execution of the function for 2 seconds, simulating a time-consuming task. Once the delay completes, the function resumes, and the remaining code is executed.Start
Task started
Task completed
End​
async
" and "await
" simplifies the code by eliminating the need for callback functions or chaining promises. It allows you to write asynchronous code in a more sequential and readable manner, making it easier to handle asynchronous operations and avoid callback hell. async
" or "sync
" based on how they handle asynchronous operations. Here's a comparison between async and sync functions:async
" keyword in their function declaration. The "async
" keyword indicates that the function contains asynchronous code and can use the "await
" keyword to pause its execution until asynchronous operations complete. An async function returns a Future that represents the eventual completion of the function.await
" keyword because they do not involve asynchronous operations. The execution of a sync function proceeds immediately to the next line after each statement.await
" keyword to pause their execution until an asynchronous operation completes. The "await
" keyword allows the function to wait for the result of an asynchronous operation before proceeding to the next line of code. The use of "await" is only valid inside an async function.return
" statement, or implicitly return "null
" if no value is specified.Future<T>
", where "T
" represents the type of the value that the function eventually returns.void main() {
syncFunction();
print('After syncFunction');
asyncFunction();
print('After asyncFunction');
}
void syncFunction() {
print('Sync function');
}
Future<void> asyncFunction() async {
print('Async function started');
await Future.delayed(Duration(seconds: 2));
print('Async function completed');
}​
Sync function
After syncFunction
Async function started
After asyncFunction
Async function completed​
syncFunction
` is a sync function, and it executes synchronously without any delays. The execution proceeds to the next line immediately after the function call.asyncFunction
` is an async function. It is marked with the "async
" keyword, allowing the use of "await
" inside the function. Inside the async function, we use `await
` before `Future.delayed
` to introduce a delay of 2 seconds. As a result, the execution of the async function pauses at the `await
` statement, allowing other code (e.g., the next `print
` statement) to execute. String? name;
int nameLength = name?.length ?? 0; // Using ?. and ?? operators to handle null​
String? name;
name ??= 'John'; // Assigning a default value if name is null​
?.
) is used to safely access properties or methods on an object. If the object is null, the entire expression evaluates to null. For example: String? name;
if (name?.isEmpty == true) {
// Code block executes only if name is not null and is empty
}​
String? name;
int nameLength = name!.length; // Asserting that name is not null​
3. Conditional Statements : String? name;
String fullName = name ?? 'Guest'; // Assigning a default value if name is null​
if
` and `else
`, can be used to explicitly handle null values. You can check if a variable is null and take appropriate actions based on that. For example: String? name;
if (name == null) {
// Code block executes if name is null
} else {
// Code block executes if name is not null
}​
Type?
`) and non-nullable (`Type
`) types. Non-nullable types guarantee that a value is never null, while nullable types allow null values. This helps in catching potential null-related issues during compilation. String? nullableName = null;
String nonNullableName = 'John';​
void main() {
printMsg();
print(test());
}
printMsg()= >
print("hello");
int test()= 123;
// returning function​
get
` keyword followed by the method name. For example: class MyClass {
int _myPrivateVar = 42;
int get myPrivateVar => _myPrivateVar;
}​
set
` keyword followed by the method name. For example: class MyClass {
int _myPrivateVar = 42;
set myPrivateVar(int value) {
_myPrivateVar = value;
}
}​
..
`) is known as the cascade notation or cascade operator. It provides a concise way to perform a sequence of operations on the same object without repeating the object reference...
`) cascade notation:class Person {
String name = '';
int age = 0;
String address = '';
void printDetails() {
print('Name: $name');
print('Age: $age');
print('Address: $address');
}
}
void main() {
var person = Person()
..name = 'John Doe'
..age = 30
..address = '123 Main St';
person.printDetails();
}​
In the example above, we define a `Person
` class with three properties: `name
`, `age
`, and `address
`. The `printDetails
` method prints the values of these properties.main
` function, we create an instance of the `Person
` class using the `var
` keyword. The double dot (`..
`) cascade notation allows us to perform multiple property assignments (`name`, `age`, `address`) on the `person` object without repeating the object reference.Name: John Doe
Age: 30
Address: 123 Main St​
`..
`) can be used with any object that has methods or properties. It allows you to chain multiple method calls or property assignments in a concise and readable way, making the code more expressive and compact. <>
`) after the class name. Type parameters represent placeholder types that are substituted with actual types when instances of the class are created. For example: class Box<T> {
T value;
Box(this.value);
}
void main() {
var box = Box<int>(42);
print(box.value); // Output: 42
}​
Box
` class is defined with a type parameter `T
`. The `Box
` class can be instantiated with different types, such as `int
`, `String
`, or custom types. The type parameter `T
` is used as the type of the `value
` property.<>
`). For example: T findFirst<T>(List<T> items) {
if (items.isNotEmpty) {
return items[0];
}
return null;
}
void main() {
var numbers = [1, 2, 3, 4, 5];
var firstNumber = findFirst<int>(numbers);
print(firstNumber); // Output: 1
}​
In the above example, the `findFirst
` function is a generic function that takes a list of type `T
` and returns the first element of the list. The type parameter `T
` is specified when calling the function.extends
` keyword followed by the type or interface that the type parameter must extend or implement. For example: class Box<T extends num> {
T value;
Box(this.value);
}
void main() {
var box1 = Box<int>(42); // OK, int extends num
var box2 = Box<double>(3.14); // OK, double extends num
var box3 = Box<String>('hello'); // Error, String does not extend num
}​
Box
` class is constrained with the `num
` type using the `extends
` keyword. This means that the type parameter `T
` must be a subtype of `num
`. Therefore, `int
` and `double
` are valid types for `T
`, but `String
` is not.try {
// Code that may throw an exception
} catch (exception) {
// Exception handling code
}​
throw
` keyword followed by an instance of an exception or an object that implements the `Exception
` class. Dart provides various built-in exception classes, such as `Exception
`, `Error
`, and their subclasses, or you can define custom exception classes by extending the `Exception
` class or any of its subclasses. void divide(int a, int b) {
if (b == 0) {
throw Exception('Division by zero is not allowed.');
}
print(a / b);
}​
divide
` function throws an instance of the `Exception
` class with a custom error message if the second argument `b
` is zero. try {
// Code that may throw an exception
} catch (exceptionType) {
// Exception handling code for exceptionType
} catch (anotherExceptionType) {
// Exception handling code for anotherExceptionType
}​
on
` keyword to catch exceptions of specific types. try {
divide(10, 0);
} catch (e) {
print('Exception occurred: $e');
}​
divide
` function is called within the try block. If an exception is thrown, it will be caught in the catch block, and the error message will be printed.
3. Finally Block :finally
` block to specify code that should always be executed, regardless of whether an exception is thrown or not. The code in the `finally` block executes regardless of whether an exception is caught or not. try {
// Code that may throw an exception
} catch (exception) {
// Exception handling code
} finally {
// Code that always executes
}​
finally
` block is useful for releasing resources or performing cleanup operations.rethrow
` keyword. This allows you to catch an exception, perform additional operations or logging, and then rethrow the same exception to be caught at a higher level. try {
divide(10, 0);
} catch (e) {
print('Exception occurred: $e');
// Perform additional operations or logging
rethrow; // Rethrow the caught exception
}​
mixin
` keyword followed by the class name. It cannot have constructors and cannot be instantiated directly. mixin LoggerMixin {
void log(String message) {
print('Log: $message');
}
}​
LoggerMixin
` that provides a `log
` method for logging messages.with
` keyword followed by the name of the mixin class. You can include multiple mixins by separating them with commas. class MyClass with LoggerMixin {
void doSomething() {
log('Doing something...');
}
}​
MyClass
` class uses the `LoggerMixin
` by including it with the `with
` keyword. As a result, the `doSomething
` method in `MyClass
` can call the `log
` method defined in the `LoggerMixin
`.
3. Mixin Application Rules : When a mixin is applied to a class, certain rules govern how the mixin's code is integrated into the class:on
` keyword is used to restrict mixins to specific types. You can specify the types or interfaces that a mixin can be applied to using the `on` keyword followed by the desired types or interfaces. This allows you to ensure that a mixin is only applied to compatible classes or interfaces.mixin LoggerMixin on SomeClass {
// Mixin code
}​
LoggerMixin
` can only be applied to classes that are subclasses of `SomeClass
`.Future
` class, which represents a value that may not be available immediately. The `async
` and `await
` keywords are used together to work with asynchronous operations in a synchronous manner, making the code more readable and easier to follow.async
` keyword is used to mark a function as asynchronous. It allows you to use the `await
` keyword within the function body to wait for the completion of asynchronous operations.await
` keyword is used to pause the execution of an `async
` function until a `Future
` completes. It allows you to extract the result of the `Future` once it's available.async
` and `await
`: Future<void> fetchData() async {
// Simulating an asynchronous operation
await Future.delayed(Duration(seconds: 2));
print('Data fetched!');
}
void main() {
print('Start');
fetchData();
print('End');
}​
Start
End
Data fetched!​
fetchData
` function is marked as `async
`, and the `await
` keyword is used to pause the execution until the `Future.delayed
` operation completes. The delay simulates an asynchronous operation, and once the delay is over, the code resumes execution, and "Data fetched!
" is printed.Future
` objects directly. This approach involves registering callbacks to be executed when a `Future
` completes. void fetchData() {
Future.delayed(Duration(seconds: 2)).then((_) {
print('Data fetched!');
});
}
void main() {
print('Start');
fetchData();
print('End');
}​
Start
End
Data fetched!​
In this example, the `then
` method is used to register a callback to be executed when the `Future.delayed
` operation completes. Once the delay is over, the callback is invoked, and "Data fetched!
" is printed.Stream
` class to handle continuous asynchronous data streams, such as real-time data feeds or event streams. Streams are a sequence of asynchronous events that can be listened to and processed. Stream<int> countDown(int from) async* {
for (int i = from; i >= 0; i--) {
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
void main() {
print('Start');
countDown(5).listen((value) {
print(value);
});
print('End');
}​
Start
End
5
4
3
2
1
0​
countDown
` function returns a `Stream
` that emits integers from a given number down to zero. The `listen
` method is used to subscribe to the stream and receive the emitted values. As the countdown progresses, the callback inside `listen
` is invoked for each emitted Isolate.spawn()
` function to create a new isolate and start its execution. The `spawn()
` function takes a callback function as an argument, which will be the entry point of the isolate. import 'dart:isolate';
void isolateFunction(SendPort sendPort) {
// Isolate execution logic
}
void main() {
Isolate.spawn(isolateFunction, null);
}​
isolateFunction
` is the entry point of the spawned isolate. It receives a `SendPort
` that can be used to communicate with the isolate.SendPort
` and `ReceivePort
` objects. The `SendPort
` is used to send messages from one isolate to another, while the `ReceivePort
` is used to receive messages. import 'dart:isolate';
void isolateFunction(SendPort sendPort) {
// Receiving messages
ReceivePort receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
receivePort.listen((message) {
print('Received message: $message');
});
// Sending messages
sendPort.send('Hello from isolate!');
}
void main() async {
ReceivePort mainReceivePort = ReceivePort();
Isolate isolate = await Isolate.spawn(isolateFunction, mainReceivePort.sendPort);
mainReceivePort.listen((message) {
print('Received message in main: $message');
isolate.kill();
});
}​
In the example above, the main isolate creates a `ReceivePort
` called `mainReceivePort
` to receive messages from the spawned isolate. The spawned isolate sends its `ReceivePort
` to the main isolate through the `SendPort
`. The main isolate listens to messages on its `mainReceivePort
` and prints them. The spawned isolate sends a message to the main isolate.SendPort
` and `ReceivePort
` objects. `SendPort
` allows you to send messages to another isolate, while `ReceivePort
` allows you to listen to incoming messages. import 'dart:isolate';
void isolateFunction(SendPort sendPort) {
sendPort.send('Hello from isolate!');
}
void main() async {
ReceivePort receivePort = ReceivePort();
Isolate isolate = await Isolate.spawn(isolateFunction, receivePort.sendPort);
receivePort.listen((message) {
print('Received message: $message');
isolate.kill();
});
}​
ReceivePort
` to listen for messages. The spawned isolate sends a message to the main isolate through the `SendPort
`. The main isolate listens for messages on its `receivePort
` and prints the received message.main()
` function serves as the entry point of a Dart program. It is the function that is executed when the program starts running. The `main()
` function is mandatory in every Dart program and is typically the first function that gets executed.main()
` function:main()
` function has a specific signature: it must be defined as a top-level function and have a return type of `void
`. It does not accept any arguments. void main() {
// Program execution starts here
}​
main()
` function is executed sequentially. It acts as the starting point of the program's execution.main()
` function must be defined at the top level of the Dart program, meaning it cannot be defined inside another function, class, or any other block of code.main()
` function acts as the last executed code block in the program. Once the execution of the `main()
` function completes, the program terminates.main()
` function allows you to define the initial logic of your Dart program. You can use it to call other functions, instantiate objects, perform calculations, handle user input, or execute any other code that needs to be executed when the program starts running. It provides a centralized location where the program's execution begins and allows you to structure and organize your code effectively. for
` loop allows you to iterate over a sequence of values for a specified number of times. It consists of an initialization statement, a condition, and an iteration statement. for (var i = 0; i < 5; i++) {
print(i);
}​
for
` loop will iterate from 0 to 4, printing the values of `i
` in each iteration.for-in
` loop is used to iterate over elements of an iterable object such as lists, sets, or strings. var myList = [1, 2, 3, 4, 5];
for (var item in myList) {
print(item);
}​
for-in
` loop iterates over each element in the `myList
` list and prints the values.while
` loop repeatedly executes a block of code as long as a given condition is true. var i = 0;
while (i < 5) {
print(i);
i++;
}​
while
` loop that prints the values of `i
` from 0 to 4.
4. do-while loop : The `do-while
` loop is similar to the `while` loop, but the condition is checked after the code block is executed. This guarantees that the code block is executed at least once. var i = 0;
do {
print(i);
i++;
} while (i < 5);​
do-while
` loop prints the values of `i
` from 0 to 4.forEach
` loop is used to iterate over elements of an iterable object and execute a function for each element. var myList = [1, 2, 3, 4, 5];
myList.forEach((item) {
print(item);
});​
forEach
` loop to iterate over each element in the `myList
` list and execute the provided function for each element. truncate()
` methods are used to truncate a floating-point number to an integer value. Dart provides two methods for truncation:truncate()
` method returns the integer obtained by discarding any fractional digits from a floating-point number towards zero. double number = 3.8;
int truncatedNumber = number.truncate();
print(truncatedNumber); // Output: 3​
truncate()
` method is called on the `number
` variable, which has a value of 3.8. The method truncates the decimal part, resulting in an integer value of 3.
2. `truncateToDouble()` : The `truncateToDouble()
` method works similarly to `truncate()
`, but it returns the result as a `double
` instead of an `int
`. double number = 5.6;
double truncatedNumber = number.truncateToDouble();
print(truncatedNumber); // Output: 5.0​
truncateToDouble()
` method is used on the `number
` variable with a value of 5.6. It truncates the decimal part and returns the result as a `double
`, resulting in the value 5.0.@override
` annotation to explicitly indicate the intention to override. class Superclass {
void someMethod() {
print('Superclass method');
}
}
class Subclass extends Superclass {
@override
void someMethod() {
print('Subclass method');
}
}​
Subclass
` overrides the `someMethod()
` from the `Superclass
` by providing its own implementation.
3. Invocation : When a method is invoked on an object of the subclass, the Dart runtime first checks if the method is overridden in the subclass. If it is, the overridden method in the subclass is executed. If not, the method in the superclass is executed. Superclass superObj = Superclass();
Subclass subObj = Subclass();
superObj.someMethod(); // Output: Superclass method
subObj.someMethod(); // Output: Subclass method​
someMethod()
` is invoked on both `superObj
` and `subObj
`. The actual implementation executed depends on the type of the object.