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:
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
final
: Declares a variable that can be assigned only once. Once assigned, its value cannot be changed.final piValue = 3.14;
const
: Declares a compile-time constant. Its value must be known at compile time and cannot be changed.const double gravity = 9.8;
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.'); }
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'); }
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!'); }
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); }
return
: Exits a function and optionally returns a value.int add(int a, int b) { return a + b; }
void
: Denotes that a function does not return any value.void printMessage(String message) { print(message); }
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:
new
: Creates a new instance of an object or invokes a constructor.
var myObject = new MyClass();
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);
}
}
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');
}
}
try
,catch
,finally
: Used for exception handling. Code inside thetry
block is executed, and if an exception occurs, it can be caught and handled in thecatch
block. Thefinally
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
}
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');
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'
show
,hide
: Used in combination withimport
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:
async
,await
: Used for asynchronous programming.async
declares a function that returns a Future, andawait
is used to pause execution until the awaited Future completes.
Future<void> fetchData() async {
// Asynchronous code
}
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;
}
}
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;
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
}
on
,catch
: Used in combination withtry
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
}
rethrow
: Used in acatch
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
}
cascade (..)
: Allows you to perform a sequence of operations on the same object.
var myList = [1, 2, 3];
myList
..add(4)
..addAll([5, 6]);
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');
deferred
: Used for lazy loading of libraries in Dart.
import 'package:my_library/my_library.dart' deferred as myLibrary;
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:
typedef
: Used to define a function type alias, making it easier to work with complex function signatures.
typedef String StringMapper(int input);
external
: Used to declare an external function implemented in another language, typically used with Dart FFI (Foreign Function Interface).
external int nativeFunction();
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;
late
: Used to declare a non-nullable variable that is initialized later in the code.
late String lateVariable;
void initializeLater() {
lateVariable = 'Initialized later';
}
lateinit
: Introduced in Dart 2.12, similar tolate
, used for late initialization but with a more concise syntax.
late String lateVariable;
void initializeLater() => lateVariable = 'Initialized later';
enum
: Used to declare enumerations, representing a set of named constant values.
enum Color { red, green, blue }
var selectedColor = Color.red;
on
: Used incatch
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
}
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
}
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'
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:
native
: Used in Dart FFI (Foreign Function Interface) to interact with native code.
@native('MyLibraryFunction')
int myDartFunction();
rethrow
: Used in acatch
block to rethrow the caught exception.
try {
// Code that might throw an exception
} catch (e) {
// Handle the exception
rethrow; // Re-throws the same exception
}
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});
}
lateinit
: Introduced in Dart 2.12, similar tolate
, used for late initialization.
lateinit String lateVariable;
void initializeLater() => lateVariable = 'Initialized later';
deferred
: Used to load libraries lazily in Dart.
import 'package:my_library/my_library.dart' deferred as myLibrary;
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'
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');
is!
: Negated form ofis
, used for type checking.
if (myObject is! String) {
print('It is not a String!');
}
late final
: Introduced in Dart 2.13, allows combininglate
andfinal
for non-nullable variables that are initialized later.
late final String lateFinalVariable;
void initializeLater() => lateFinalVariable = 'Initialized later';
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:
is!
: Negated form ofis
, used for type checking.
if (myObject is! String) {
print('It is not a String!');
}
typedef
: Used to define a function type alias, making it easier to work with complex function signatures.
typedef String StringMapper(int input);
late
: Used to declare a non-nullable variable that is initialized later in the code.
late String lateVariable;
void initializeLater() {
lateVariable = 'Initialized later';
}
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;
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
}
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;
on
,catch
: Used in combination withtry
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
}
on
: Used incatch
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
}
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;
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) {
// ...
}
}
rethrow
: Used in acatch
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:
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
}
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!');
}
}
sync
: Used with generator functions to declare synchronous iteration.
Iterable<int> generateNumbers() sync* {
for (int i = 0; i < 5; i++) {
yield i;
}
}
async
: Used with generator functions to declare asynchronous iteration.
Stream<int> generateAsyncNumbers() async* {
for (int i = 0; i < 5; i++) {
yield i;
}
}
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;
}
}
await
: Used in asynchronous functions to wait for the completion of a Future.
Future<void> fetchData() async {
var data = await fetchDataFromServer();
print(data);
}
yield*
: Used in generator functions to delegate to another generator.
Iterable<int> generateMoreNumbers() sync* {
yield* generateNumbers(); // Delegating to another generator
}
lateinit
: Introduced in Dart 2.12, similar tolate
, used for late initialization.
late String lateVariable;
void initializeLater() => lateVariable = 'Initialized later';
late final
: Introduced in Dart 2.13, allows combininglate
andfinal
for non-nullable variables that are initialized later.
late final String lateFinalVariable;
void initializeLater() => lateFinalVariable = 'Initialized later';
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.
Subscribe to my newsletter
Read articles from Parth Chauhan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Parth Chauhan
Parth Chauhan
I'm Computer Engineering Student. Learning Status DSA in Java, Dart Development, Python in Django Development. Best part is Communication Skills, Marketing, Accounting.