Dart Syntax: Keywords

Dart Syntax: Keywords

Dart, keywords are reserved words that have a special meaning and cannot be used as identifiers (such as variable or function names). These keywords are part of the language's syntax and are used to define the structure and logic of the code.

Keywords play a crucial role in the interpretation and execution of code by providing specific instructions or denoting certain constructs within the programming language. Examples of keywords include var, final, if, else, for, switch, class, return, and many others.

Using keywords appropriately is essential for writing valid and meaningful code in a programming language. They are predefined and serve specific roles in the language's grammar and semantics, helping developers create logic, handle control flow, and structure their programs.

Here is an explanation of some key Dart keywords:

  1. var: Declares a variable with an inferred type. Dart will determine the type based on the assigned value.

     var age = 25; // Dart infers the type as int
    
  2. final: Declares a variable that can be assigned only once. Once assigned, its value cannot be changed.

     final piValue = 3.14;
    
  3. const: Declares a compile-time constant. Its value must be known at compile time and cannot be changed.

     const double gravity = 9.8;
    
  4. if, else: Conditional statements used for executing different blocks of code based on a specified condition.

     if (age >= 18) {
       print('You are an adult.');
     } else {
       print('You are a minor.');
     }
    
  5. for: Initiates a loop that iterates over a sequence of values or performs a specific action a predetermined number of times.

     for (var i = 0; i < 5; i++) {
       print('Count: $i');
     }
    
  6. switch, case, default: Provides a way to handle multiple conditions in a concise manner.

     switch (day) {
       case 'Monday':
         print('It\'s the start of the week.');
         break;
       case 'Friday':
         print('Weekend is approaching.');
         break;
       default:
         print('Enjoy your day!');
     }
    
  7. break, continue: Control flow statements used to exit a loop prematurely (break) or skip the rest of the loop and continue with the next iteration (continue).

     for (var i = 0; i < 10; i++) {
       if (i == 5) {
         break; // Exit the loop when i equals 5
       }
       print(i);
     }
    
  8. return: Exits a function and optionally returns a value.

     int add(int a, int b) {
       return a + b;
     }
    
  9. void: Denotes that a function does not return any value.

     void printMessage(String message) {
       print(message);
     }
    
  10. class, extends, implements: Keywords for defining and working with classes and inheritance.

    class Animal {
      void makeSound() {
        print('Some generic sound');
      }
    }
    
    class Dog extends Animal {
      @override
      void makeSound() {
        print('Woof! Woof!');
      }
    }
    

These are just a subset of Dart keywords, and there are more keywords in Dart used for various purposes. Understanding and using these keywords correctly is fundamental for effective Dart programming.

Certainly! Here are more Dart keywords along with brief explanations:

  1. new: Creates a new instance of an object or invokes a constructor.
var myObject = new MyClass();
  1. this: Refers to the current instance of the class within which it is used.
class Example {
  var value;

  Example(this.value);

  void printValue() {
    print(this.value);
  }
}
  1. super: Refers to the superclass or parent class of the current class.
class Parent {
  void display() {
    print('Parent class');
  }
}

class Child extends Parent {
  @override
  void display() {
    super.display();
    print('Child class');
  }
}
  1. try, catch, finally: Used for exception handling. Code inside the try block is executed, and if an exception occurs, it can be caught and handled in the catch block. The finally block contains code that is executed regardless of whether an exception occurred.
try {
  // Code that might throw an exception
} catch (e) {
  // Handle the exception
} finally {
  // Code that always runs
}
  1. assert: A debugging aid that evaluates a boolean expression. If the expression is false, an assertion failure occurs, and an optional message can be provided.
assert(number >= 0, 'Number must be non-negative');
  1. import, export: Used for importing and exporting libraries in Dart.
import 'dart:math'; // Import the 'dart:math' library
export 'my_library.dart'; // Export symbols from 'my_library.dart'
  1. show, hide: Used in combination with import to selectively import or hide specific parts of a library.
import 'dart:math' show sqrt; // Only import the 'sqrt' function from 'dart:math'
import 'my_library.dart' hide UtilityClass; // Import all symbols except 'UtilityClass'

These additional keywords cover various aspects of Dart programming, including object-oriented features, exception handling, and library management.

Certainly! Here are ten more Dart keywords with brief explanations:

  1. async, await: Used for asynchronous programming. async declares a function that returns a Future, and await is used to pause execution until the awaited Future completes.
Future<void> fetchData() async {
  // Asynchronous code
}
  1. yield: Used in a generator function to produce a sequence of values lazily.
Iterable<int> generateNumbers() sync* {
  for (int i = 0; i < 5; i++) {
    yield i;
  }
}
  1. is, as: Used for type checking (is) and type casting (as).
if (myObject is String) {
  print('It is a String!');
}

var myString = myObject as String;
  1. with: Used in a class declaration to mixin the members of another class.
class A {
  void methodA() {}
}

class B with A {
  // Class B now has the members of class A
}
  1. on, catch: Used in combination with try for catching specific types of exceptions.
try {
  // Code that might throw an exception
} on SomeException catch (e) {
  // Handle only SomeException
} catch (e) {
  // Handle other exceptions
}
  1. rethrow: Used in a catch block to rethrow the exception that was caught.
try {
  // Code that might throw an exception
} catch (e) {
  // Handle the exception
  rethrow; // Re-throws the same exception
}
  1. cascade (..): Allows you to perform a sequence of operations on the same object.
var myList = [1, 2, 3];
myList
  ..add(4)
  ..addAll([5, 6]);
  1. assert: A debugging aid that evaluates a boolean expression. If the expression is false, an assertion failure occurs.
assert(number >= 0, 'Number must be non-negative');
  1. deferred: Used for lazy loading of libraries in Dart.
import 'package:my_library/my_library.dart' deferred as myLibrary;
  1. sync*, async*: Used to declare synchronous (sync*) and asynchronous (async*) generator functions.
Iterable<int> generateSyncNumbers() sync* {
  // Synchronous generator function
}

Stream<int> generateAsyncNumbers() async* {
  // Asynchronous generator function
}

These keywords cover a range of features in Dart, including asynchronous programming, type checking, exception handling, and more.

Certainly! Here are ten more Dart keywords with brief explanations:

  1. typedef: Used to define a function type alias, making it easier to work with complex function signatures.
typedef String StringMapper(int input);
  1. external: Used to declare an external function implemented in another language, typically used with Dart FFI (Foreign Function Interface).
external int nativeFunction();
  1. extension: Introduced in Dart 2.7, it allows adding new functionality to existing types.
extension StringExtension on String {
  int get lengthSquared => length * length;
}

// Usage
var result = 'Dart'.lengthSquared;
  1. late: Used to declare a non-nullable variable that is initialized later in the code.
late String lateVariable;

void initializeLater() {
  lateVariable = 'Initialized later';
}
  1. lateinit: Introduced in Dart 2.12, similar to late, used for late initialization but with a more concise syntax.
late String lateVariable;

void initializeLater() => lateVariable = 'Initialized later';
  1. enum: Used to declare enumerations, representing a set of named constant values.
enum Color { red, green, blue }

var selectedColor = Color.red;
  1. on: Used in catch blocks to catch exceptions of a specific type.
try {
  // Code that might throw an exception
} on FormatException catch (e) {
  // Handle FormatException
} catch (e) {
  // Handle other exceptions
}
  1. mixin: Used to define mixins, a way to reuse a class's code in multiple class hierarchies.
mixin Jumping {
  void jump() {
    print('Jumping!');
  }
}

class Person with Jumping {
  // Person now has the 'jump' method
}
  1. show, hide (in import): Used to selectively import or hide specific parts of a library.
import 'dart:math' show min;
// Only import the 'min' function from 'dart:math'
  1. runes: Used to represent Unicode code points in Dart.
var heart = '\u2665'; // Unicode code point for heart

These keywords cover additional Dart features, such as type aliasing, external functions, late initialization, enums, and more.

Certainly! Here are ten more Dart keywords:

  1. native: Used in Dart FFI (Foreign Function Interface) to interact with native code.
@native('MyLibraryFunction')
int myDartFunction();
  1. rethrow: Used in a catch block to rethrow the caught exception.
try {
  // Code that might throw an exception
} catch (e) {
  // Handle the exception
  rethrow; // Re-throws the same exception
}
  1. required: Used with named parameters in constructors to specify that the parameter must be provided when creating an instance.
class Person {
  final String name;

  Person({required this.name});
}
  1. lateinit: Introduced in Dart 2.12, similar to late, used for late initialization.
lateinit String lateVariable;

void initializeLater() => lateVariable = 'Initialized later';
  1. deferred: Used to load libraries lazily in Dart.
import 'package:my_library/my_library.dart' deferred as myLibrary;
  1. show, hide (in export): Used to selectively export or hide specific parts of a library.
export 'my_library.dart' show MyClass;
// Only export 'MyClass' from 'my_library.dart'
  1. assert: A debugging aid that evaluates a boolean expression. If the expression is false, an assertion failure occurs.
assert(number >= 0, 'Number must be non-negative');
  1. is!: Negated form of is, used for type checking.
if (myObject is! String) {
  print('It is not a String!');
}
  1. late final: Introduced in Dart 2.13, allows combining late and final for non-nullable variables that are initialized later.
late final String lateFinalVariable;

void initializeLater() => lateFinalVariable = 'Initialized later';
  1. show, hide (in mixin): Used to selectively include or exclude members of a mixin.
mixin Jumping on Animal {
  @override
  void move() {
    super.move();
    print('Jumping!');
  }
}

These keywords cover a range of Dart features, including required parameters, deferred loading, assertion, type checking, and more.

Certainly! Here are ten more Dart keywords:

  1. is!: Negated form of is, used for type checking.
if (myObject is! String) {
  print('It is not a String!');
}
  1. typedef: Used to define a function type alias, making it easier to work with complex function signatures.
typedef String StringMapper(int input);
  1. late: Used to declare a non-nullable variable that is initialized later in the code.
late String lateVariable;

void initializeLater() {
  lateVariable = 'Initialized later';
}
  1. extension: Introduced in Dart 2.7, it allows adding new functionality to existing types.
extension StringExtension on String {
  int get lengthSquared => length * length;
}

// Usage
var result = 'Dart'.lengthSquared;
  1. sync*, async*: Used to declare synchronous (sync*) and asynchronous (async*) generator functions.
Iterable<int> generateSyncNumbers() sync* {
  // Synchronous generator function
}

Stream<int> generateAsyncNumbers() async* {
  // Asynchronous generator function
}
  1. extension: Introduced in Dart 2.7, it allows adding new functionality to existing types.
extension StringExtension on String {
  int get lengthSquared => length * length;
}

// Usage
var result = 'Dart'.lengthSquared;
  1. on, catch: Used in combination with try for catching specific types of exceptions.
try {
  // Code that might throw an exception
} on SomeException catch (e) {
  // Handle only SomeException
} catch (e) {
  // Handle other exceptions
}
  1. on: Used in catch blocks to catch exceptions of a specific type.
try {
  // Code that might throw an exception
} on FormatException catch (e) {
  // Handle FormatException
} catch (e) {
  // Handle other exceptions
}
  1. extension: Introduced in Dart 2.7, it allows adding new functionality to existing types.
extension StringExtension on String {
  int get lengthSquared => length * length;
}

// Usage
var result = 'Dart'.lengthSquared;
  1. covariant: Used in the context of method parameters in a class hierarchy, allowing more flexibility with type parameters.
class Box<T> {
  void insert(covariant T item) {
    // ...
  }
}
  1. rethrow: Used in a catch block to rethrow the exception that was caught.
try {
  // Code that might throw an exception
} catch (e) {
  // Handle the exception
  rethrow; // Re-throws the same exception
}

These additional Dart keywords cover various aspects of Dart programming, including extension methods, type aliasing, generator functions, and more.

Certainly! Here are ten more Dart keywords:

  1. with: Used in a class declaration to include the members of another class, known as a mixin.
class Flyer {
  void fly() {
    print('Flying!');
  }
}

class Bird with Flyer {
  // Bird now has the 'fly' method from the Flyer mixin
}
  1. show, hide (in mixin): Used to selectively include or exclude members of a mixin.
mixin Jumping on Animal {
  @override
  void move() {
    super.move();
    print('Jumping!');
  }
}
  1. sync: Used with generator functions to declare synchronous iteration.
Iterable<int> generateNumbers() sync* {
  for (int i = 0; i < 5; i++) {
    yield i;
  }
}
  1. async: Used with generator functions to declare asynchronous iteration.
Stream<int> generateAsyncNumbers() async* {
  for (int i = 0; i < 5; i++) {
    yield i;
  }
}
  1. yield: Used in generator functions to produce a sequence of values lazily.
Iterable<int> generateNumbers() sync* {
  for (int i = 0; i < 5; i++) {
    yield i;
  }
}
  1. await: Used in asynchronous functions to wait for the completion of a Future.
Future<void> fetchData() async {
  var data = await fetchDataFromServer();
  print(data);
}
  1. yield*: Used in generator functions to delegate to another generator.
Iterable<int> generateMoreNumbers() sync* {
  yield* generateNumbers(); // Delegating to another generator
}
  1. lateinit: Introduced in Dart 2.12, similar to late, used for late initialization.
late String lateVariable;

void initializeLater() => lateVariable = 'Initialized later';
  1. late final: Introduced in Dart 2.13, allows combining late and final for non-nullable variables that are initialized later.
late final String lateFinalVariable;

void initializeLater() => lateFinalVariable = 'Initialized later';
  1. show, hide (in mixin): Used to selectively include or exclude members of a mixin.
mixin Jumping on Animal {
  @override
  void move() {
    super.move();
    print('Jumping!');
  }
}

These keywords cover additional Dart features, including mixins, generator functions, and asynchronous programming constructs.