Open In App

Dart – Keywords

Improve
Improve
Like Article
Like
Save
Share
Report

Dart Keywords are the reserved words in Dart programming Language which has some special meaning to the compiler. These keywords are case-sensitive and cannot be used to name variables, classes, and functions.

There are in total 61 keywords in Dart programming language:

 

Keywords Table
abstract       else            import             super as                enum         
in                    switch assert          export        interface          sync 
async          extends        is                    this await          extension    
library             throw break         external       mixin               true
case           factory         new                 try class           final            
catch          false            null                  typedef  on                   var
const          finally          operator          void continue     for              
part                

while

covariant    Function      rethrow           with
default        get               return              yield  deferred      hide            
set                   do if                 show            dynamic           implements
static                 

Most of these keywords have already been discussed in the various sub-sections of the Dart Programming Sections:-

1. abstract:- abstract modifier is used to define an abstract class—a class that can’t be instantiated. Abstract classes are useful or defining interfaces, often with some implementation.

Dart




// Understanding Abstract class in Dart
 
// Creating Abstract Class
abstract class Gfg {
    // Creating Abstract Methods
    void say();
    void write();
}
 
class Geeksforgeeks extends Gfg{
    @override
    void say()
    {
        print("Yo Geek!!");
    }
 
    @override
    void write()
    {
        print("Geeks For Geeks");
    }
}
 
main()
{
    Geeksforgeeks geek = new Geeksforgeeks();
    geek.say();
    geek.write();
}


2. as:- as operator is used to cast an object to a particular type if and only if when we are sure that the object is of that type.

Example:

Dart




void main() {
  (employee as Person).firstName = 'Bob';
}


 

 

3. assert: The assert statement is used to debug the code and it uses boolean condition for testing. If the boolean expression in the assert statement is true then the code continues to execute, but if it returns false then the code ends with Assertion Error.

 

Syntax"  assert(condition, optionalMessage);

 

Dart




void main()
{
String geek = "Geeks For Geeks";
assert(geek != "Geeks For Geeks");
print("You Can See This Line Geek as a Output");
}


 

 

4. async: When an async function is called, a future is immediately returned and the body of the function is executed later. As the async function’s body is executed, the Future returned by the function call will be completed along with its result. In the above example, calling demo() results in the Future. 

 

Dart




void hello() async {
print('something exciting is going to happen here...');
}


 

 

5. await: Await expressions makes you write the asynchronous code almost as if it were synchronous. In general, an await expression has the form as given below:

 

Dart




void main() async {
 await hello();
 print('all done');
}


 

 

6. break: break is used for stopping the loop and switch case whenever the condition is met. Eg:  Break in while loop

 

Dart




void main()
{
while (true) {
 
 if (shutDownRequested()) break;
 processIncomingRequests();
}
 
Break in Switch Case:-
 
var command = 'OPEN';
 
switch (command) {
 case 'CLOSED':
   executeClosed();
   break;
case 'DENIED':
   executeDenied();
   break;
 case 'OPEN':
   executeOpen();
   break;
 default:
   executeUnknown();
}
}


 

 

7. case: case is the same as it is in other programming languages it is used with switch statement .

 

Dart




void main() {
  ar command = 'OPEN';
switch (command) {
  case 'CLOSED':
    executeClosed();
    break;
  case 'PENDING':
    executePending();
    break;
  case 'APPROVED':
    executeApproved();
    break;
  case 'DENIED':
    executeDenied();
    break;
  case 'OPEN':
    executeOpen();
    break;
  default:
    executeUnknown();
}
}


 

 

8. catch: catch is used with the try block in dart to catch exceptions in the program.

 

syntax:-
try {  
  // program that might throw an exception  
}  
on Exception1 {  
  // code for handling exception 1
}  
catch Exception2 {  
  // code for handling exception 2
}

 

Example:

 

Dart




void main() {
int geek = 10;
try{
    var geek2 = geek ~/ 0;
    print(geek2);
}
catch(e){
    print(e);
}
finally {
    print("Code is at end, Geek");
}
}


 

 

9. class: class in dart as same as a class in other object-oriented programming languages. A class is a group of objects which have common properties. It is a template or blueprint from which objects are created. It is a logical entity.

 

Syntax:
class  class_name
{
 //statements
}

 

Dart




class geeks
{
  String var= "Geeks for Geeks";
  void print()
  {
    print(var);
  }
}


 

 

10. continue: continue statement is used to break one iteration in the loop whenever the condition matches and start the next iteration.

 

Example:

 

Dart




void main() {
  for(int i=0;i<6;i++)
  {
    if(i==4)
     continue;
    print(i);
  }
}


 

 

11. const: const is used for making a variable constant throughout the program. The const keyword isn’t just for declaring constant variables. We can also use it to create constant values and declare constructors that create constant values. Any variable can have a constant value.

 

Example:

 

Dart




void main() {
  var foo = const [];
final bar = const [];
 
// Equivalent to `const []`
const baz = [];
}


 

 

You can omit const from the initializing expression of a const declaration, like for baz above.

 

12. covariant:- covariant keyword to tell the analyzer that you are overriding a parameter’s type with a subtype, which is invalid.This removes the static error and instead checks for an invalid argument type at runtime.

 

Example:

 

Dart




void chase(Animal x) { ... }
}
 
class Mouse extends Animal { ... }
 
class Cat extends Animal {
 
 @override
 void chase(covariant Mouse x) { ... }
 
}


 

 

13. default: default statement is used in switch case when no condition matches then the default statement is executed.

 

Example:

 

Dart




void main() {
  var command = 'GEEKS FOR GEEKS';
switch (command) {
  case 'CLOSED':
    print('Closed');
    break;
  case 'PENDING':
    print('PENDING');
    break;
  case 'APPROVED':
    print('APPROVED');
    break;
  case 'DENIED':
    print('DENIED');
    break;
  case 'OPEN':
    print('OPEN');
    break;
  default:
    print('DEFAULT STATEMENT EXECUTED');
}
}


14. deferred:- Deferred loading (also called lazy loading) allows a web app to load a library on-demand when the library is needed. 

Here are some cases when deferred loading is used:

  1. To reduce a web app’s initial startup time.
  2. To perform A/B testing—trying out alternative implementations of an algorithm, for example.
  3. To load rarely used functionality, such as optional screens and dialogs.

15. do:  do is used with while for do-while loop.

Example:

Dart




void main() {
  int i=1; 
    do
       print(i); 
          i++; 
    }while(i<=5); 
}


16. dynamic:- dynamic is used to declare a dynamic variable that can store any value in it be it string or int, it is the same as var in javascript.

Example:

Dart




void main()
{
dynamic x=1;
 
print(x);
 
x="xx";
print(x);
}


 

 

17. else:  else is used with if statement, it is used to test the condition,  if block is executed, if the condition is true otherwise else block, is executed.

 

if(condition)
{
 statements;
}
else
{
statements;
}

 

Example:

 

Dart




void main() {
  var i=10;
  if(i==9)
      print('Hello, Geeks!');
  else
    print('Geeks for Geeks');
}


18. enum: enums, are a special kind of class used to represent a fixed number of constant values.

Dart




// dart program to print all the
// elements from the enum data class
 
// Creating enum with name Gfg
enum Gfg {
     
// Inserting data
Welcome, to, GeeksForGeeks
}
 
void main() {
     
// Printing the value
// present in the Gfg
for (Gfg geek in Gfg.values) {
    print(geek);
}
}


19. export: export is used to create a new library and use other libraries you want to make available automatically when using your package, 

Example:

Dart




library mylib;
 
export 'otherlib.dart';


 

 

20. extends: extends to create a subclass, and super to refer to the superclass:

 

Example:

 

Dart




class gfg
{
  void disp();
}
class geeks extends gfg
{
  void show()
  {
    //statement;
  }
}


21. extensions: extensions are a way through which we can add functionality to the existing libraries.

Here’s an example of using an extension method on String named parseInt() that’s defined in string_apis.dart:

Example:

Dart




import 'string_apis.dart';
void main() {
  print('Hello, Geeks!');
   
  // Use a String method.
  print('42'.padLeft(5));
  print('42'.parseInt());
}


22. external:- An external function is a function whose body is provided separately from its declaration. An external function may be a top-level function or a method.

eg: external String toString();

23. factory:- factory is used when implementing a constructor that doesn’t always create a new instance of its class.

In the following example, the Logger factory constructor returns objects from a cache, and the Logger.fromJson factory constructor initializes a final variable from a JSON object.

Example:

Dart




class Logger {
 
 final String name;
 
 bool mute = false;
 
 // _cache is library-private, thanks to
 // the _ in front of its name.
 
 static final Map<String, Logger> _cache =
     <String, Logger>{};
 factory Logger(String name) {
   return _cache.putIfAbsent(
       name, () => Logger._internal(name));
 }
 
 factory Logger.fromJson(Map<String, Object> json) {
   return Logger(json['name'].toString());
 }
 
 Logger._internal(this.name);
 
 void log(String msg) {
   if (!mute) print(msg);
 }
}


24. false:- false is one of the boolean types of dart apart from true.

Dart




void main()
{
  var gfg=false;
  print(gfg);
}


 

 

25. final:- final is used when we don’t intend to change a variable in the rest of the program.

 

Dart




void main()
{
  final gfg=false;
  gfg=true;
  print(gfg);
}


26. finally: finally is a block, which is used to place codes that should be executed even if there is an exception in the program. finally block is placed after the try block and whenever any error occurs the control goes to the finally block and it is executed.

Example:

Dart




void main()
{
  try {
      int x=9,y=0;
      int res = x ~/ y;
   
   on IntegerDivisionByZeroException catch(e) {
      print(e);
   }
  finally
  {
    print('finally block executing');
  }
}


 

 

27. for:- for is used in ‘for loop’, it is the same as for loops in other programming languages. 

 

Example:

 

Dart




void main() {
  for(int i=0;i<5;i++)
      print(i);
}


28. Function:- Dart is a true object-oriented language, so even functions are objects and have a type, “Function”. It means that functions can be assigned to variables or passed as arguments to other functions. 

Example:

Dart




int gfg()
{
  int obj;
  return obj=1;
}
void main() {
  print(gfg());
}


29. get:- Getters and setters are special methods that provide read and write access to an object’s properties.

Example:

Dart




   }
     
   void set s_name(String name) {
      this.name = name;
   }
    
   void set s_age(int age) {  
         this.age = age;
       
   }
    
   int get s_age {
      return age;    
   }
void main() {
   Student obj = new Student();
   obj.stud_name = 'DART';
   obj.stud_age = 10;
   print(s1.stud_name);
   print(s1.stud_age);
}


30. hide:- hide is used when only part of a library, you can selectively import the library. For example:

// Import only foo.
import 'package:lib1/lib1.dart' show foo;
// Import all names EXCEPT foo.
import 'package:lib2/lib2.dart' hide foo;

31. if:- if is a conditional statement, which is used check condition and if the conditions turn out to be true then the block attaching next to it is executed until the condition turns to be false.

Example:

Dart




void main()
{
  int x=5;
  if(x!=0)
  {
    print(x);
  }
  else
    print('else block executing');
}


32. import:- import keyword is used for libraries and other files in the particular dart program.

Example:

Dart




import 'dart:html';


33. implements:- implements is used to implement the interface in the program.

Example:

Dart




class Person {
   
  // In the interface, but visible
  // only in this library.
  final _name;
 
  // Not in the interface, since
  // this is a constructor.
  Person(this._name);
 
  // In the interface.
  String greet(String who) => 'Hello, $who. I am $_name.';
}
 
// An implementation of the Person interface.
class Impostor implements Person {
  get _name => '';
 
  String greet(String who) => 'Hi $who. Do you know who I am?';
}
 
String greetBob(Person person) => person.greet('Bob');
 
void main() {
  print(greetBob(Person('Kathy')));
  print(greetBob(Impostor()));
}


34. in:- in is used in for-in loop .for-in loop is used when we are iterating over an iterable (such as list or set).

Example:

Dart




void main() {
  var lists = [1, 2, 3];
  for (var obj in lists) print(obj);
}


35. interface:- The interface in the dart provides the user with the blueprint of the class, that any class should follow if it interfaces that class i.e. if a class inherits another it should redefine each function present inside an interfaced class in its way. 

Example:

Dart




void main(){
     
// Creating Object
// of the class Gfg
Gfg geek1= new Gfg();
     
// Calling method
// (After Implementation )
geek1.printdata();
}
 
// Class Geek (Interface)
class Geek {
void printdata() {
    print("Hello Geek !!");
}
}
 
// Class Gfg implementing Geek
class Gfg implements Geek {
void printdata() {
    print("Welcome to GeeksForGeeks");
}
}


36. is:- is is a type test operator which is handy for checking types at runtime. is return true if the object is of specified type.

Example:

if (employee is Person) {
 // Type check
 employee.firstName = 'Bob';
}

37. libraries:- The import and library directives can help you create a modular and shareable code base. Libraries not only provide APIs, but are a unit of privacy: identifiers that start with an underscore (_) are visible only inside the library. Every Dart app is a library, even if it doesn’t use a library directive.

For example, Dart web apps generally use the dart:html library, which they can import like this:

import 'dart:html';

38. mixin:- Mixins are a way of reusing a class’s code in multiple class hierarchies.

Example:

Dart




class Musician extends Performer with Musical {
 
 // ···
 
}
 
class Maestro extends Person
   with Musical, Aggressive, Demented {
 
 Maestro(String maestroName) {
   name = maestroName;
   canConduct = true;
 }
}


 

 

39. part:- part is a keyword through which a library is split into multiple dart files and those files are imported in the dart program. 

 

Example:

 

Dart




export 'src/cascade.dart';
export 'src/handler.dart';
export 'src/handlers/logger.dart';
export 'src/hijack_exception.dart';
export 'src/middleware.dart';
export 'src/pipeline.dart';
export 'src/request.dart';
export 'src/response.dart';
export 'src/server.dart';
export 'src/server_handler.dart';


40. new:- new is a keyword which is used to create instance of a class .

syntax: class class_name = new class_name( [arguments]);

Example:

Dart




class gfg {
  var name = 'geeksforgeeks';
  void display() {
    print(name);
  }
}
 
void main() {
  gfg obj = new gfg();
  obj.display();
}


41. null: Uninitialized variables that have a nullable type have an initial value of null. (If you haven’t opted into null safety, then every variable has a nullable type.) Even variables with numeric types are initially null, because numbers like everything else in Dart are objects.

Example:

Dart




void main() {
  var x;
  print(x);
}


42. on:- on is a block, which is used with try block whenever we have a specified type of exception to catch .

Example:

Dart




void main()
{
  try
  {
    int x=10,y;
    y=x~/0;
  }
  on IntegerDivisionByZeroException
  {
    print("divide by zero exception");
  }
}


43. operator:- Operators are instance methods with special names. Dart allows you to define operators with the following names:

< > +
| ^ / [ ]
[ ]= <= >= ~/
~ & * <<
>> % ==  

Example:

Dart




class Vector {
  final int x, y;
 
  Vector(this.x, this.y);
 
  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
 
  // Operator == and hashCode not shown.
  // ···
}
 
void main() {
  final v = Vector(2, 3);
  final w = Vector(2, 2);
 
  assert(v + w == Vector(4, 5));
  assert(v - w == Vector(0, 1));
}


44. part:- The part is used to split a library into multiple files and then use it . But it is recommended to avoid using part and create mini libraries instead.

Eg: Dividing the src folder into multiple files and using it in dart program.

creating multiple parts of shelf root directory

export 'src/cascade.dart';
export 'src/handler.dart';
export 'src/handlers/logger.dart';
export 'src/hijack_exception.dart';
export 'src/middleware.dart';
export 'src/pipeline.dart';
export 'src/request.dart';
export 'src/response.dart';
export 'src/server.dart';
export 'src/server_handler.dart';

45.rethrow:- rethrow is used to partially handle exceptions while allowing it to propagate further.Rethrow can be used to make sure that exception is properly handled internally before it propagates to other callers.

Example:

Dart




void misbehave() {
  try {
    dynamic foo = true;
    print(foo++); // Runtime error
  } catch (e) {
    print('misbehave() partially handled ${e.runtimeType}.');
    rethrow; // Allow callers to see the exception.
  }
}
 
void main() {
  try {
    misbehave();
  } catch (e) {
    print('main() finished handling ${e.runtimeType}.');
  }
}


 

 

46. return:- return is used for returning value of a function/method.

 

Example:

 

Dart




int fact(int n) {
  if (n <= 1)
    return 1;
  else
    return n * fact(n - 1);
}
 
void main() {
  int n = 5;
  print(fact(5));
}


47. set:- set is used for initializing variables in the program, it comes in handy when we have to set many variables in a program.

Example:

Dart




class Rectangle {
 
 double left, top, width, height;
 
 Rectangle(this.left, this.top, this.width, this.height);
 
 // Define two calculated properties: right and bottom.
 double get right => left + width;
 set right(double value) => left = value - width;
 
 double get bottom => top + height;
 set bottom(double value) => top = value - height;
 
}
void main() {
 
 var rect = Rectangle(3, 4, 20, 15);
 assert(rect.left == 3);
 rect.right = 12;
 assert(rect.left == -8);
}


48. show:-show is used to import a selective file from a library.

Example:

// Import only foo.
import 'package:lib1/lib1.dart' show foo;

49. static:- The static keyword is used to implement class-wide variables and methods.

Example:

Dart




//Variables
class Queue {
 
 static const initialCapacity = 16;
 // ···
}
 
void main() {
 
 assert(Queue.initialCapacity == 16);
}
 
//Methods
import 'dart:math';
 
class Point {
 
 double x, y;
 Point(this.x, this.y);
 
 static double distanceBetween(Point a, Point b) {
 
   var dx = a.x - b.x;
   var dy = a.y - b.y;
   return sqrt(dx * dx + dy * dy);
 }
}
 
void main() {
 
 var a = Point(2, 2);
 var b = Point(4, 4);
 var distance = Point.distanceBetween(a, b);
 assert(2.8 < distance && distance < 2.9);
 print(distance);
 
}


 

 

50.super:- super is used to call methods and variables of the parent class.

 

Example:

 

Dart




// Creating Parent class
class SuperGeek {
    String geek = "Geeks for Geeks";
}
 
// Creating child class
class SubGeek extends SuperGeek {
 
    // Accessing parent class variable
    void printInfo()
    {
        print(super.geek);
    }
}
 
void main()
{
    // Creating child class object
    SubGeek geek = new SubGeek();
 
    // Calling child class method
    geek.printInfo();
}


51.switch:- switch keyword is used in switch case statement, switch case is the simplified version of the nested if-else statement.

Example:

Dart




void main()
{
    int gfg = 1;
    switch (gfg) {
    case 1: {
        print("GeeksforGeeks number 1");
    } break;
    case 2: {
        print("GeeksforGeeks number 2");
    } break;
    case 3: {
        print("GeeksforGeeks number 3");
    } break;
    default: {
        print("This is default case");
    } break;
    }
}


52. sync:- To implement a synchronous generator function,  the function body is marked as sync*.

Example:

Dart




Iterable<int> naturalsTo(int n) sync* {
 
 int k = 0;
 while (k < n) yield k++;
}


 

 

53. this:- this keyword represents an implicit object pointing to the current class object. It refers to the current instance of the class in a method or constructor. The this keyword is mainly used to eliminate the ambiguity between class attributes and parameters with the same name.

 

Example:

 

Dart




// Dart program to illustrate
// this keyword
void main()
{
Student s1 = new Student('S001');
}
 
class Student
{
// defining local st_id variable
var st_id;
Student(var st_id)
{
    // using this keyword
    this.st_id = st_id;
    print("GFG - Dart THIS Example");
    print("The Student ID is : ${st_id}");
}
}


 

 

54. throw:- throw keyword is used to throw explicit raise an exception. It should be  handled properly otherwise it will cause the program to stop abruptly.

 

Example:

 

Dart




void gfg(int flag) {
  if (flag < 0) {
    throw new FormatException();
  }
}
 
void main() {
  try {
    gfg(-2);
  } catch (e) {
    print('Exception caught!');
  }
}


 

 

55. true:- true is a boolean value which is a compile time constant.

 

Example:

 

Dart




void main()
{
  bool gfg=true;
  print(gfg);
}


 

 

56. try:-try is a block in dart in which those codes are kept which can raise an error in the program.A try block is followed by at least one on/catch block or a finally block.

 

Dart




void main() {
  int x = 10, y;
  try {
    y = x ~/ 0;
  } on Exception catch (e) {
    print(e);
  }
}


 

 

57. typedef:- A typedef, or function-type alias, gives a function type a name that you can use when declaring fields and return types. A typedef retains type information when a function type is assigned to a variable.

 

Example:

 

Dart




typedef Compare = int Function(Object a, Object b);
 
class SortedCollection {
 
 Compare compare;
 SortedCollection(this.compare);
 
}
 
// Initial, broken implementation.
int sort(Object a, Object b) => 0;
 
void main() {
 
 SortedCollection coll = SortedCollection(sort);
 assert(coll.compare is Function);
 assert(coll.compare is Compare);
}


 

 

58. var:-  var is used to declare a variable in the dart program.

 

Example: 

 

var str="gfg";

 

59. void:- void is a built-in type which indicates that the value is never used.It is generally used with function to specify that it has no return type.

 

Example:

 

Dart




// void types shows that
// it will return nothing
void main() 
{
  print('Hello, Geeks!');
}


60.while:- while is used in  while loop.While loop evaluates the condition before entering the loop ,that’s why it is known as entry control loop

Example:

Dart




void main() {
  int x = 5;
  while (x != 0) {
    print(x);
    x--;
  }
}


 

 

61. with:- with is used for using mixins in the dart program.

 

Syntax:-

 

class B {  //B is not allowed to extend any other class other than object
 method(){
    ....
 }
}
class A with B {
 ....
    ......
}
void main() {
 A a = A();
 a.method();  //we got the method without inheriting B
}

 

Example:

 

Dart




mixin Geeks {
  bool java = false;
  bool c = false;
  bool python = false;
 
  void WhichLanguageYouKnow() {
    if (java) {
      print('I know Java');
    } else if (c) {
      print('I know C');
    } else {
      print('I know Dart');
    }
  }
}
class Gfg with Geeks
{
  int x;
}
void main()
{
  Gfg ob=new Gfg();
  ob.WhichLanguageYouKnow();
}


62. yield:- yield keyword is used with sync* function to deliver the output of the synchronous function.

Example:

Dart




void main() {
  print('Hello, Geeks!');
}




Last Updated : 03 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads