Professional Documents
Culture Documents
Dart language concepts, syntax, and usage
Dart language concepts, syntax, and usage
com /a-quick-reference-for-dart-language-concepts-syntax-and-usage/
MAIN FUNCTION
void main() {
print('Hello, World!');
}
VARIABLES
OPERATORS
// Arithmetic operators
var sum = 10 + 20; // addition
var difference = 40 - 30; // subtraction
var product = 2 * 5; // multiplication
var quotient = 15 / 3; // division
var remainder = 20 % 3; // modulus
// Comparison operators
var isEqual = (5 == 5); // equality
var notEqual = (5 != 6); // inequality
var greaterThan = (5 > 3); // greater than
var lessThan = (5 < 7); // less than
var greaterOrEqual = (5 >= 5); // greater than or equal to
var lessOrEqual = (5 <= 5); // less than or equal to
// Logical operators
var and = true && false; // logical and
var or = true || false; // logical or
var not = !true; // logical not
// Assignment operators
var x = 10; // simple assignment
x += 5; // addition assignment (same as x = x + 5)
x -= 2; // subtraction assignment (same as x = x - 2)
x *= 3; // multiplication assignment (same as x = x * 3)
x /= 2; // division assignment (same as x = x / 2)
x %= 4; // modulus assignment (same as x = x % 4)
// Conditional operator
var isEven = (x % 2 == 0) ? true : false; // if-else shorthand
COMMENTS
METADATA
// Metadata provides additional information about the code to tools and other
programs
// Metadata provides additional information about the code to tools and other
programs
// Metadata can be added to classes, methods, variables, and parameters using the @
symbol
@deprecated
void myDeprecatedFunction() {
// deprecated function code here
}
class MyClass {
@override
void myMethod() {
// method code here
}
}
@immutable
class MyImmutableClass {
final int myProperty;
const MyImmutableClass(this.myProperty);
}
@proxy
class MyDynamicClass {
// proxy code here
}
// Dart code is organized into libraries, which are collections of related code
// Libraries are defined using the 'library' keyword, followed by the name of the
library
library my_library;
// Code from other libraries can be accessed using the 'import' keyword
// The 'as' keyword can be used to give an imported library a different name
import 'package:flutter/cupertino.dart' as cupertino;
// The 'show' and 'hide' keywords can be used to selectively import or hide parts of
a library
import 'package:my_package/my_module.dart' show myFunction;
import 'package:my_package/my_module.dart' hide myPrivateFunction;
// Code can also be exported from a library using the 'export' keyword
export 'my_other_library.dart';
// Libraries can have a part directive to include source code from other files
part 'my_file.dart';
TYPES
• built-in types
• collections
• operators
// Dart has operators and control flow statements for working with collections
// Spread operator
var numbers = [1, 2, 3];
var moreNumbers = [0, ...numbers]; // spread operator inserts contents of
numbers into moreNumbers
// For loops
for (var i = 0; i < numbers.length; i++) {
print(numbers[i]); // prints each element in numbers
}
// For-in loops
for (var number in numbers) {
print(number); // prints each element in numbers
}
// forEach method
numbers.forEach((number) => print(number)); // prints each element in numbers
using a lambda function
// Map method
var doubledNumbers = numbers.map((number) => number * 2); // creates a new list
with each element in numbers multiplied by 2
// Where method
var evenNumbers = numbers.where((number) => number % 2 == 0); // creates a new
list with only the even elements in numbers
// Reduce method
var sum = numbers.reduce((value, element) => value + element); // computes the
sum of all elements in numbers
// Conditional expressions
var age = 21;
var isLegal = age >= 18 ? 'Legal' : 'Illegal'; // ternary operator - sets
isLegal to 'Legal' if age is greater than or equal to 18, and 'Illegal'
otherwise
• generics
// Generic classes
class Box<T> {
T item;
Box(this.item);
// Generic methods
T getFirst<T>(List<T> items) => items[0];
// Usage examples
var intBox = Box<int>(10); // creates a Box that can hold integers
var stringBox = Box<String>('hello'); // creates a Box that can hold strings
• typedef
// Usage examples
bool isEven(int number) => number % 2 == 0;
bool isOdd(int number) => number % 2 == 1;
• if-else Statements
if (condition) {
// code to execute if the condition is true
} else {
// code to execute if the condition is false
}
• for loops
// The for loop is used to execute code repeatedly for a specific number of
times
• while loops
// The while loop is used to execute code repeatedly while a condition is true
while (condition) {
// code to execute while the condition is true
}
• do-while loops
// The do-while loop is used to execute code repeatedly at least once, and then
as long as a condition is true
do {
// code to execute at least once
} while (condition);
• switch statements
switch (variable) {
case value1:
// code to execute if variable equals value1
break;
case value2:
// code to execute if variable equals value2
break;
default:
// code to execute if variable does not equal any of the cases
break;
}
ERROR HANDLING
// Defining a class
class Person {
String name;
int age;
// A named constructor
Person.fromJson(Map<String, dynamic> json) {
name = json['name'];
age = json['age'];
}
EXTENSION
String greet() {
return "Hello, my name is $name and I am $age years old";
}
}
void main() {
var person = Person(name: "Alice", age: 25);
print(person.introduce("New York")); // prints "Hi, my name is Alice and I am from
New York"
}
ENUM
enum Flavor {
vanilla,
chocolate,
strawberry,
mint,
}
// Example usage
void main() {
var myFlavor = Flavor.chocolate;
printFlavorInfo(myFlavor);
}
MIXIN
// Defining a mixin
mixin Dancer {
void dance() {
print("Dancing...");
}
}
// Defining a class that uses the mixin
class Person with Dancer {
String name;
int age;
CALLABLE CLASSES
// Example usage
void main() {
var hello = Greeting("Hello");
var goodbye = Greeting("Goodbye");
void main() {
// Declaring nullable variables with the "?" operator
String? name;
int? age;
// Using the "!" operator to assert that a nullable variable is not null
name = "Alice";
age = 25;
print("Hello, my name is ${name!} and I am ${age!} years old");
// Using the "?? " operator to provide a default value for a nullable variable
String? jobTitle;
String message = "Hello";
message += jobTitle ?? "there";
print(message);
class Person {
final String name;
final int age;
ASYNCHRONOUS PROGRAMMING
• future : object that represents a value that may not be available yet.
void main() {
// Creating a Future object that resolves to a value after a delay
Future<String> delayedHello(int seconds) {
return Future.delayed(Duration(seconds: seconds), () => "Hello");
}
// prints :
// Before the future
// After the future
// Hello, world!
// prints :
// Before the future
// After the future
// Hello, world!
• the async keyword is used to mark the main function as an asynchronous function, and the await
keyword is used to pause the execution of the function until the delayedHello() Future has
completed.
• This allows the code to be written in a more synchronous style, where each line of code is
executed one after the other, without blocking the event loop.
GitHub
View Github