You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
A Dart cheat sheet with the most important concepts, functions, methods, and more. A complete quick reference for beginners.
plugins
copyCode
Getting Started {.cols-2}
hello.dart
// top-level function where app execution startsvoidmain(){
print("Hello World!"); // Print to console
}
Every app has a main() function
Variables
int x =2; // explicitly typedvar p =5; // type inferred - Generic var with type inferencedynamic z =8; // variable can take on any type
z ="cool"; // cool// if you never intend to change a variable use final or const. Something like this:final email ="temid@gmail.com"; // Same as var but cannot be reassignedfinalString email ="temid@gmail.com"; // you can't change the valueconst qty =5; // Compile-time constant
Datatypes
int age =20; // integers, range -2^63 to 2^63 - 1double height =1.85; // floating-point numbers// You can also declare a variable as a numnum x =1; // x can have both int and double values
x +=2.5;
print(x); //Print: 3.5String name ="Nicola";
bool isFavourite =true;
bool isLoaded =false;
String interpolation
// can use single or double qoutes for String typevar firstName ='Nicola';
var lastName ="Tesla";
//can embed variables in string with $String fullName ="$firstName $lastName";
// concatenate with +var name ="Albert "+"Einstein";
String upperCase ='${firstName.toUpperCase()}';
print(upperCase); //Print: NICOLA
Comments
// This is a normal, one-line comment./// This is a documentation comment, used to document libraries,/// classes, and their members. Tools like IDEs and dartdoc treat/// doc comments specially./* Comments like these are also supported. */
multiline String
For multiline String we have to use ''' your text'''for example
print('''My long string''');
//this will show long string//this will help for only long strings
print(2+3); //Print: 5print(2-3); //Print: -1print(2*3); //Print: 6print(5/2); //Print: 2.5 - Result is a doubleprint(5~/2); //Print: 2 - Result is an intprint(5%2); //Print: 1 - Remainderint a =1, b;
// Increment
b =++a; // preIncrement - Increment a before b gets its value.
b = a++; // postIncrement - Increment a AFTER b gets its value.//Decrement
b =--a; // predecrement - Decrement a before b gets its value.
b = a--; // postdecrement - Decrement a AFTER b gets its value.
Equality and relational operators
print(2==2); //Print: true - Equalprint(2!=3); //Print: true - Not Equalprint(3>2); //Print: true - Grater thanprint(2<3); //Print: true - Less thanprint(3>=3); //Print: true - Greater than or equal toprint(2<=3); //Print: true - Less than or equal to
Logical operators
// !expr inverts the expression (changes false to true, and vice versa)// || logical OR// && logical ANDbool isOutOfStock =false;
int quantity =3;
if (!isOutOfStock && (quantity ==2|| quantity ==3)) {
// ...Order the product...
}
Control Flows : Conditionals {.cols-2}
if and else if
if(age <18){
print("Teen");
} elseif( age >18&& age <60){
print("Adult");
} else {
print("Old");
}
switch case
enumPet {dog, cat}
Pet myPet =Pet.dog;
switch(myPet){
casePet.dog:print('My Pet is Dog.');
break;
casePet.cat:print('My Pet is Cat.');
break;
default:print('I don\'t have a Pet');
}
// Prints: My Pet is Dog.
Control Flows : Loops
while loop
while (!dreamsAchieved) {
workHard();
}
while loop check condition before iteration of the loop
do-while loop
do {
workHard();
} while (!dreamsAchieved);
do-while loop verifies the condition after the execution of the statements inside the loop
for loop
for(int i=0; i<10; i++){
print(i);
}
var numbers = [1,2,3];
// for-in loop for listsfor(var number in numbers){
print(number);
}
for in loop
// Define a list of numbersvar numbers = [1, 2, 3, 4, 5];
// Use a for-in loop to iterate over the listfor (var number in numbers) {
print(number);
}
// Define a list of stringsvar fruits = ['Apple', 'Banana', 'Cherry'];
// Use a for-in loop to iterate over the listfor (var fruit in fruits) {
print(fruit);
}
Collections {.cols-2}
Lists
// ordered group of objectsvar list = [1, 2, 3];
print(list.length); //Print: 3print(list[1]); //Print: 2// other ways of list declaration and initializationsList<String> cities =<String>["New York", "Mumbai", "Tokyo"];
// To create a list that’s a compile-time constantconst constantCities =const ["New York", "Mumbai", "Tokyo"];
Sets
// A set in Dart is an unordered collection of unique items.var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'};
// to create an empty setvar names =<String>{};
Set<String> names = {}; // This works, too.//var names = {}; // Creates a map, not a set.
Maps
// a map is an object that associates keys and valuesvar person =Map<String, String>();
// To initialize the map, do this:
person['lastName'] ='Tesla';
print(person); //Print: {firstName: Nicola, lastName: Tesla}print(person['lastName']); //Print: Teslavar nobleGases = {
// Key: Value2:'helium',
10:'neon',
18:'argon',
};
Functions {.cols-2}
Functions
// functions in dart are objects and have a typeintadd(int a, int b){
return a+b;
}
// functions can be assigned to variablesint sum =add(2,3); // returns: 5// can be passed as arguments to other functionsint totalSum =add(2, add(2,3)); // returns : 7
Arrow Syntax (=>)
// functions that contain just one expression, you can use a shorthand syntaxboolisFav(Product product) => favProductsList.contains(product);
Anonymous (lambda) functions
// small one line functions that dont have nameintadd(a,b) => a+b;
// lambda functions mostly passed as parameter to other functionsconst list = ['apples', 'bananas', 'oranges'];
list.forEach(
(item) =>print('${list.indexOf(item)}: $item'));
//Prints: 0: apples 1: bananas 2: oranges
// abstract class—a class that can’t be instantiated// This class is declared abstract and thus can't be instantiated.abstractclassAbstractContainer {
// Define constructors, fields, methods...voidupdateChildren(); // Abstract method.
}
Getters Setters
// provide read and write access to an object’s propertiesclassCat {
String name;
// getterStringget catName {
return name;
}
// settervoidsetcatName(String name){
this.name = name;
}
}
Implicit interfaces {.cols-2}
A basic interface
// A person. The implicit interface contains greet().classPerson {
// In the interface, but visible only in this library.finalString _name;
// Not in the interface, since this is a constructor.Person(this._name);
// In the interface.Stringgreet(String who) =>'Hello, $who. I am $_name.';
}
// An implementation of the Person interface.classImpostorimplementsPerson {
Stringget _name =>'';
Stringgreet(String who) =>'Hi $who. Do you know who I am?';
}
StringgreetBob(Person person) => person.greet('Bob');
voidmain() {
print(greetBob(Person('Kathy'))); // Hello, Bob. I am Kathy.print(greetBob(Impostor())); // Hi Bob. Do you know who I am?
}
Extending a class
classPhone {
voiduse(){
_call();
_sendMessage();
}
}
// Use extends to create a subclassclassSmartPhoneextendsPhone {
voiduse(){
// use super to refer to the superclasssuper.use();
_takePhotos();
_playGames();
}
}
Exceptions
Throw
// throws or raises and exceptionthrowIntegerDivisionByZeroException();
// You can also throw arbitrary objectsthrow"Product out of stock!";
Catch
try {
int c =3/0;
print(c);
} onIntegerDivisionByZeroException {
// A specific exceptionprint('Can not divide integer by 0.')
} onExceptioncatch (e) {
// Anything else that is an exceptionprint('Unknown exception: $e');
} catch (e) {
// No specified type, handles allprint('Something really unknown: $e');
}
Finally
// To ensure that some code runs whether or not an exception is throwntry {
cookFood();
} catch (e) {
print('Error: $e'); // Handle the exception first.
} finally {
cleanKitchen(); // Then clean up.
}
Futures
Async Await
// functions which are asynchronous: they return after setting up a possibly time-consuming operation// The async and await keywords support asynchronous programmingFuture<String> login() {
String userName="Temidjoy";
returnFuture.delayed(
Duration(seconds:4), () => userName);
}
// Asynchronousmain() async {
print('Authenticating please wait...');
print(awaitlogin());
}
Extensions {.cols-2}
Why use extensions? {.row-span-2}
// Extensions allow you to add methods to existing// classes without modifying them.// Instead of defining a util class.classStringUtil {
staticboolisValidEmail(String str) {
final emailRegExp =RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
return emailRegExp.hasMatch(str);
}
}
print(StringUtil.isValidEmail('someString')); //Print: false// We can define an extension which will be applied// on a certain type.extensionStringExtensionsonString {
boolget isValidEmail {
final emailRegExp =RegExp(r"^[a-zA-Z0-9.]+@[a-zA-Z0-9]+\.[a-zA-Z]+");
return emailRegExp.hasMatch(this);
}
}
print('test@example.com'.isValidEmail); //Print: trueprint('SomeString'.isValidEmail); //Print: false
Generic Extensions
// allows you to apply the same logic to a range of types.extensionNumGenericExtensions<Textendsnum> onT {
TaddTwo() =>this+2asT;
}
print(7.addTwo()); // Print: 9
int x; // The initial value of any object is null// ?? null aware operator
x ??=6; // ??= assignment operator, which assigns a value of a variable only if that variable is currently nullprint(x); //Print: 6
x ??=3;
print(x); // Print: 6 - result is still 6print(null??10); // Prints: 10. Display the value on the left if it's not null else return the value on the right
// to insert multiple values into a collection.var list = [1, 2, 3];
var list2 = [0, ...list];
print(list2.length); //Print: 4
Cascade notation (..)
// allows you to make a sequence of operations on the same object// rather than doing thisvar user =User();
user.name ="Nicola";
user.email ="nicola@g.c";
user.age =24;
// you can do thisvar user =User()
..name ="Nicola"
..email ="nicola@g.c"
..age =24;
Conditional Property Access
userObject?.userName
//The code snippet above is equivalent to following:
(userObject !=null) ? userObject.userName :null//You can chain multiple uses of ?. together in a single expression
userObject?.userName?.toString()
// The preceeding code returns null and never calls toString() if either userObject or userObject.userName is null
enum in dart
defination:Anenum (short for"enumeration") is a special data type that enables a variable to be a set of predefined constants. Enums are used to define variables that can only take one out of a small set of possible values. They help make code more readable and less error-prone by providing meaningful names to these sets of values.
// Define the enumenumTrafficLight {
red,
yellow,
green
}
// A function that prints a message based on the traffic light statevoidprintTrafficLightMessage(TrafficLight light) {
switch (light) {
caseTrafficLight.red:print('Stop!');
break;
caseTrafficLight.yellow:print('Get ready...');
break;
caseTrafficLight.green:print('Go!');
break;
}
}
voidmain() {
// Example usage of the enumTrafficLight currentLight =TrafficLight.green;
// Print the message for the current traffic light stateprintTrafficLightMessage(currentLight);
}