Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Dart Flash Cards

version: 2.0

by: Vandad Nahavandipoor

covers: Dart 2.14.4

Twitter, LinkedIn, YouTube

Data Types Variables Dart Keywords Getters Switch Throw Rethrow


Data types are ways of telling Dart what kind of data stored is stored in the memory.
A variable is a named piece of information with a data type, that contains data in the Dart is the language that sits behind Flutter, Google’s revolutionary UI framework. Keywords are words in a programming language that are reserved for the language Getters are properties of classs that have computed return values. They need to have a A switch is a conditional statement for enums in Dart. Switches are usually used to Dart supports exceptions. Exceptions are a way for the program to be able to not only To rethrow an exception is to indicate to the consumer of your code that you could not
They make it easier for the programmer and for the computer to understand what they memory, be it in the stack or in the heap. Variables usually have a name and a data Quoting Dart’s own website: “Dart is a client-optimized language for developing fast itself. In Dart there are variaty of keywords that are reserved for the language and data type and they also have a name and include the keyword “get” in them. For take action based on values of a variable that is of the enum type. Although you ca use detect, but also propagate errors down the line. The “throw” keyword in Dart allows the handle the exception on your own and need the consumer to instead handle the
are dealing with and at the same time you will minimize the risk of calculating invalid type and they either contain a value or not (optionality). There are naming conventions apps on any platform. Its goal is to offer the most productive programming language shouldn’t be used otherwise as variable names for instance. Some of these words are, instance, if you have a class called Person that has “firstName” and “lastName” if-statements as well, the code can get quite long and difficult to read using if- code to indicate that an exception has occurred which needs to then be handled by exception. Rethrowing exceptions is very useful to improve the quality of your code
operations such as adding a number to text, an opreation whose result might not be for variables and other rules as to what data they can be assigned to based on their for multi-platform development, paired with a flexible execution runtime platform for “break”, “false”, “true”, “finally”, “const”, “enum”, “else”, “abstract” and many more which properties, you can write a property called “fullName” that has a getter which simply statements. That’s why switch is present in Dart and many other languages to allow whoever the consumer of the code is. The convention is to throw classes that are of and to ensure that your catch statements don’t just catch everything and keep the
easily understood by the computer data types. app frameworks.” are documented by the good folks at Google. returns the “firstName” and the “lastName” with a space between them. you to take action based on the value inside an enum variable. type Exception but in reality you can throw even a String or an Integer. caller in the dark. Rethrow where you can’t handle the exception.

More info More info Further reading Further reading Further reading Further reading Further reading Further reading

Dart - Data Types - GeeksforGeek Dart Programming - Variables - Tutorialspoin Dart programming language - dart.de Language tour - keywords - dart.de Dart getters and setters - dev.t Switch Case Statement - Tutorialspoin Futures Error Handling - dart.de DO use rethrow to rethrow a caught exception - dart.de
Dart Programming - Data Types - TutorialsPoin Dart Variables - W3School A tour of the Dart language - dart.de Dart keywords - w3add Getters and setters - dart.de Switch and Case - dart.de Dart Programming - Exceptions - Tutorialspoin Throw, Catch and Finally - learndartprogramming.co
The Dart type syste Variables and types in Dart - Suragc Dart Tutorials - dart.de Dart Keywords - Javatpoin Dart Getters and Setters - W3School dart Tutorial - Switch Case - riptutoria Dart Try Catch - TutorialKar Error handling in Flutter - medium.co
Dart Data Types - W3School Dart - Variables - GeeksforGeek Dart (programming language) - Wikipedi Dart - Keywords - GeeksforGeek Getter and Setter Methods in Dart - GeeksforGeek Switch Case in Dart - GeeksforGeek Dart Introduction: Exception handling - Uday Hiwaral Error handling - semantic-portal.ne
Video: Basics of Dart, DataTypes Dart Variables - TutorialKart Dart packages - pub.dev Keywords (Reserved Words) in Dart - Codesansar Getters and setters - Flutter by Example Dart Switch Case Statement - W3Schools Throw, Catch and Finally - learndartprogramming.com Exceptions and Error Handling in Dart and Flutter - Jilli Boutique

Examples Examples Examples Examples Examples Examples Examples Examples


1
/*
1
// here is a simple enu
1
final name = 'Foo'; // length of this string is 3

1
/*
1
/*
2
in this case both the words "abstract" and
2
enum Animal { dog, cat }

1
class Person {
1
// this is the most common form of exception
2
try {

1
// This is an example of a integer
2
below are all examples of variables whose value can
2
Dart has many built in features, such as support for
3
"class" are keywords, or as some may call them,
2
final String firstName;
3

2
10
3
be changed at compile and run time
3
many data types such as integers and doubles
4
reserved words!
2
// throwing, throwing an object of type Exception
3
final value = name[10]; // out of bounds

3
final String lastName;
4
// and a function that can describe it

3
// this is a string inside single quotation marks
4
*/
4
*/
5
*/
3
throw Exception('This is another one');
4
print(value);

4
const Person(this.firstName, this.lastName);
5
void describe(Animal myAnimal) {

4
'Vandad Nahavandipoor'
5
var foo = 10;
5
final ex1 = 1;
6
abstract class Animal {
4
// but you can also throw strings
5
} catch (e) {

5

6
switch (myAnimal) {

5
throw 'My simple exception';
6
if (e is RangeError) {

5
// this is a double precision value
6
foo = foo + 1; // add 1 to foo
6
final ex2 = 1.2;
7

6
/*
7
case Animal.dog:

6
3.14
7

7
void func() {
8
}
6
// or even integers
7
// we can't handle this so we rethrow it to the

7
this getter, or computed property, returns the result
8
print('This is a dog');

7
// and this is a list
8
var bar = 'Bar';
8
// and also support for functions
9

7
throw 404; // this works too, you can throw ints
8
// calling function that will then bre responsible

8
of concatenating the firstName and the lastName
9
break;

[1, 2, 3]
}
// here the word "const" is a keyword
8
// ArgumentError extends Error
9
// for handling it

8
9
bar *= 2; // Bar becomes BarBar now
9
10

9
properties into its own String result
10
case Animal.cat:

9
// we can also have hashmaps
10

10
// and also function type definitions
11
const name = 'Foo Bar';
9
throw ArgumentError(' nvalid argument');
10
rethrow;

11
print('This is a cat');

10
*/
10
// you can even throw instances of your own
11
} else {}

10 {'key1': 'value1', 'key2': 'value2'} 11


var baz = 1.2;
11
typedef MyCallback = void Function(int);
12

11
String get fullName => '$firstName $lastName';
12
break;

12 baz = baz + 3; // baz is now 4.2 12 // plus many more 13


// and here the word "final" is a keyword
11 // classes, they don't have to have a superclass 12
print(e);

12 } 13
}

14 final age = 32; 13 }


14 }

Double Integer String Class Void While and Do While Async Yield
A double is a double precision floating point value. This is to say that the container of An integer is a value that can be described by a whole number, up to a limit, dictated by A string in Dart is text usually surrounded by single quotation marks ‘like so’. If the A class is metadata around a type or multiple types. A class can have properties and Void is a datatype in Dart as it is in many other languages. Though rarely or almost Both “while” and “do” are reserved/key words in Dart meaning that they have a special Function in Dart can either produce no value, or a value synchronously, or a value The yield keyword in Dart allows you to indicate to the Dart compiler that your
this type can contain values with decimal points, such as 1.2, or 3.14. Integer values on its container variable. An example of an integer is 1, 100, 1000, and so on. Integers can string object itself contains single quotation marks such as “let’s”, then it’s usually methods. Imagine a Person class, a property of this class could be “age” while a never used as a data type for a variable, it is used extensively as a datatype for meaning for the Dart compiler. They are used to create loops. The difference between asynchronously. An asynchronous function is a function that goes off and does work generator function or your asynchronous stream function is producing a value. For
the other hand don’t have the capacity to contain a decimal point. Values of type be either signed or unsigned. A signed integer can be either positive or negative, while surrounded by double quotation marks. Dart recomments that all strings by default be metohd could be “run”. Classes can either be abstract or concrete. Classes can then be functions where the function can carry out a piece of work that doesn’t necessarily While and Do-While is that While specifies its loop condition up front and the program and comes back later producing a value, or even void. The “async” keyword in Dart is a instance if you have a synchronous function that produces an iterable of values from 0
Double can also be “demoted” or type-cast to a value of type integer and vice versa. In an unsigned integer can only contain positive values, from and including 0 up to the surrounded by single quotation marks unless there is a good reason for them to not to. instantiated in order to create objects. An object is therefore a copy of that class in produce a return value. For instance, the “print()” function in Dart has the return value loops until the condition is not met anymore. Do-while performs its initial work and way to mark up a function as an asynchronous function, meaning that the function to n, you can simply create a loop in the function and yield your values instead of
the case of Integer to Double, the type will be promoted! limit dictated by the data type. Strings can be compile time constants. memory and can be individually modified. of “void” since it produces no return values! then checks the condition at the end! doesn’t completely immediately upon being invoked. having to construct a list inside the function. Uses also for sync generators!

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

Double-precision floating-point format - Wikipedi Integer - Wikipedi String class - dart:core library - api.dart.de Dart Classes and Object - Javatpoin The curious case of void in Dart - medium.co Dart Programming - do while Loop - Tutorialspoin Asynchronous programming: futures, async, await - dart.de Difference between yield and yield* in Dart - newbedev.co
Double-Precision Floating Point - IB Numbers in Dart - Dart.de Dart Programming - String - Tutorialspoin Dart Programming - Classes - Tutorialspoin Functions in Dart - CodingPizz Dart do while Loop - W3School dart:async library - dart.de What is Yield Keyword In Flutter - flutteragency.co
double class - dart:core librar int class in Dart - api.flutter.de Exploring String methods in Dart - Darshan Kawa Language samples - dart.de Dart Programming - Functions - Tutorialspoin Dart (DartLang) Introduction: while and do-while loops - Mediu Asynchronous programming: Streams - dart.de Asynchronous programming: Streams - dart.de
What is a double in Dart? - Educative.i Integer in Dart - Educative.i Working with Strings in Dart/Flutter - FrontBacken Dart - Classes And Objects - GeeksforGeek Dart Functions - W3School Dart do while Loop - Javatpoin Exploring Async Programming In Dart & Flutter - medium.co Dart Generators - Javatpoin
Floating-point arithmetic - Wikipedia Integer class - Pub.dev Dart/Flutter String Functions & Operators - Bezkoder Dart Class - TutorialKart Dart function - working with functions in Dart - etCode
Z Dart Do While Loop Tutorial With Examples - FlutterRDart Dart's async/await in Flutter - Educative.io Generators in Dart - GeeksforGeeks

Examples Examples Examples Examples Examples Examples Examples Examples


1
// here is an example of a function that uses "while"

1
void performWork() {
1
// here is a synchronous generator function that produces

2
// in order to print "value", as many times as "count"
1
// this function is marked as "async" meaning that inside

1
// a person's age is a good example of an integer
1
/*
2
// this is a function that does not return
2
// three integers, 1, 2, 3, using the yield keyword

3
void printValueWithWhile(String value, {required int count}) {
2
// it we are allowed to use the "await" keyword in order to

1
/*
2
final age = 20;
1
// a string is text
2
this is an example of a class with 3 properties namely
3
// a value, indicated by its void return-type
3
terable<int> threeNumbers() sync* {

4
var counter = 0;
3
// wait on the result of other functions marked with "async"

2
a double value, or a double precision floating
3

2
final myName = 'Vandad Nahavandipoor';
3
age, address and name. here the properties are final
4
}
4
yield 1;

5
while (counter++ < count) {
4
Future<int> fetchStatusCode(String urlStr) async {

3
point value refers to a value that can contain
4
// you can perform various operators such as
3
/*
4
meaning that their values cannot be changed after being
5

5
yield 2;

6
print(value);
5
final url = Uri.parse(urlStr);

4
decimals, in this example, the .2 is the decimal
5
// division on an integer
4
it can contain numbers as well but this number
5
assigned to. the class also has a constructor with
6
// this value will automatically become of type
6
yield 3;

7
}
6
// for instance the "getUrl" function is an async function

5
value after the integer value of 1
6
final dividedByTwo = age / 2;
5
will not be considered an integer anymore
6
the prefix of const
7
// void as well since the result of perfomWork()
7
}

8
}
7
// that we can "await" on since our function itself is

6
*/
7

6
and is from this point on a string, meaning that
7
*/
8
// is being assigned to it
8
// and here is the equivalent async function marked as

9

8
// marked as "async"

7
final fooBar = 1.2;
8
// multiplication is done through the * operator
7
you cannot add another integer to it
8
class Person {
9
final foo = performWork();
9
// async* that generates 3 integers, 1, 2, 3, inside the

10
// and the same function using the do statement
9
final getResult = await HttpClient().getUrl(url);

8
final plusTwo = fooBar + 2;
9
final multipliedByTwo = age * 2;
8
*/
9
final String name;
10

10
// stream using yield

11
void printValueWithDo(String value, {required int count}) {
10
// smae for the close() function, it's async so we can

9
final againPlusTwo = fooBar + 2.0;
10

9
final myAge = '20';
10
final String address;
11
// you should not be doing the above code and
11
Stream<int> threeNumbersStream() async* {

12
var counter = 0;
11
// await on it since we are an async function too

10
// a string cannot be added to a double by default
11
// functions or getters can also return
10
// so this code will not compile
11
final int age;
12
// instead should just perform the work by calling
12
yield 1;

13
do {
12
final result = await getResult.close();

11 final invalid = fooBar + 'Foo Bar'; // compile-error 12


// values of type integer
11 final invalid = myAge + 30; 12
const Person(this.name, this.address, this.age);
13
// the function with no assignment
13
yield 2;

14
print(value);
13
return result.statusCode;

13 final lengthOfName = 'Foo Bar'.length; 13 } 14 performWork(); 14


yield 3;

15
} while (++counter < count);
14 }
15 }
16 }

Constants Final Lists Sets Subclassing Interface Abstract Classes Static


A constant, or a compile-time constant, is a value whose internals do not change Final is a variable modifer that makes a variable assignable only once. Notice that final Lists, as their name denote, can contain more than one object at once. Objects are not While a list can contain duplicate items, a set’s job is to filter out duplicate items. Subclassing is the ability of a class to inherit functionality from another class. Let’s say An interface is the public API of a class. Dart has no support for the interface keyword An abstract class is by default a class that cannot be instantiated with a constructor The static keyword is used to define class-wide functionality for your classes. Whereas
during the entire execution of the program. An example of a constant value in Dart is has nothing to do with constant. A final variable can only be assigned to once, whereas named. They are accessible by their index. The first item is always at index 0, item 2 is Objects have hash values using which a set determines if two objects are alike. These you have a class called Animal with a function called “walk()”. A dog or a cat are also but implicitly exports an interface for every class based on its public facing API. Think since abstract classes cannot have constructors. Abstract classes can have default a property or a member function of a class is per-class instantiation, a static function
the value “1”, or a constant instance of a class called Person whose first name is “Foo” a constant variable can not only be assigned only once, but also has to be a constant! at index 1 and so on. That’s why they call lists zero-based, meaning that their indexes hash values are usually integers that custom objects can override and define manually. animals so if you create a class called Dog, you can subclass the Animal class and of an interface as the public face of a class, in that a class can have private internals implementation for their methods though and can have factory methods to make them is for the entire class and is shared across all instances of the same class. Use static
and last name is “Bar”. Those values will not change for the entire lifetime of the For instance, if you read a user’s name from the console into a variable, that value can start at 0. A list can contain heterogenous objects, meaning that objects inside the list Built-in types have hash values that you don’t have to play with in order to have them inherit the “walk()” function in your Dog class without you having to reinvent the wheel that it doesn’t expose to the public, and some public facing API that is called its appear as though they can be instantiated. Use abstract classes to define your high functions or variables wherever you want to define a class-wide interface for your
program. They can however be changed before compiling the project. be stored into a final variable, but not a constant! don’t necessarily have to be of the same type. work together with sets, objects such as strings and integers for instance. and write that function from scratch. interface which the consumer can interact with. level interfaces and have other classes inherit functionality from abstract classes. consumers.

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

Dart final and const - dart.de Final and const - dart.de Lists - dart.de Sets - dart.de Dart Inheritance - Javatpoin Dart Programming - Interfaces - Tutorialspoin Abstract Classes in Dart - GeeksforGeek Dart - Static Keyword - GeeksforGeek
Compile-time constants and variables - Newbede Dart - Const And Final Keyword - GeeksforGeek Dart Programming - Lists - Tutorialspoin Set class - dart:core librar Dart - Concept of Inheritance - GeeksforGeek Interface in Dart - Mediu Abstract Classes and Abstract Methods in Dart - Mediu Dart static Keyword - W3Schools | W3Add
Constants and Variables - Rebu Difference between Const and Final in Dart - Jeroen Ouwehan Dart/Flutter List Tutorial with Examples - BezKode Dart Sets - W3School Exploring Inheritance and Composition in Dart & Flutter - Mediu Dart Interfaces - W3Schools | W3Add Dart Abstract Classes - Javatpoin Dart static Keyword - Javatpoin
Constant (computer programming) - Wikipedi Difference Between the const and final keywords - Somyarajsinh List class - dart:core library - Flutter AP Dart Programming - Collection Set - Tutorialspoin Inheritance, Polymorphism, and Composition - dart.academ Interface in Dart - GeeksforGeek Dart Abstract classes - W3Schools | W3Add Dart static keyword - techLo
Constants in Programming Language - Toppr Difference Between Constant and Final Explained Example Dart Lists - W3Schools Dart Sets - Javatpoint Dart Programming - Classes - Tutorialspoint Dart Interfaces - Javatpoint Abstract Classes in Dart Programming - Tutorialspoint Using Static Methods in Dart and Flutter - Kindacode

Examples Examples Examples Examples Examples Examples Examples Examples


1
// our super-class
1
// every class in Dart has an implicit interface
1
abstract class Animal {

1
/*
2
class Animal {
2
class Animal {
2
// this function in this abstract class has default
1
// here is our class with one static constant field

1
/*

1
/*
2
here is an example of 3 strings placed
3
void run() {
3
// this function is public since it doesn't start
3
// implementation that doesn't need to be implemented
2
class Car {

1
/*
2
a set definition starts with curly brackets and ends

2
this will create an integer variable named
3
inside a list, the list has 3 items. using
4
print('Running');
4
// with an underscore, hence it's part of the public
4
// by every class extending Animal
3
// this static field will be shared amongst all

2
foo in this example is a compile-time constant
3
with a closing bracket. it cannot contain duplicate values.

3
"age" whose value is initially set to 20
4
the index of 0 you can access 'foo', with the

4
duplication of values is defined by their hash values.
5
}
5
// interface of the Animal class
5
void run() {
4
// instances of the Car class, meaning that various

3
meaning that its value cannot be changed after
4
and cannot be changed after it has been declared
5
index of 1 you can get to 'bar' and with

4
it has been assigned to.
5
*/
6
}
6
void run() {
6
print('Running');
5
// instances of this class will not have their own

5
*/
6
the index of 2 you can get to 'baz'
7
// empty for now
7
}
7
}
6
// copy of the wheelCount static field, instead

5
*/
6
const ages = {

6
final age = 20;
7
*/
8
class Cat extends Animal {
8
// and so is this function
8
// but this function will need to be implemented by
7
// they all share the same constant

6
const foo = 'Foo';
7
10, 20, 30

7
final otherAge = age + 20;
8
const names = ['foo', 'bar', 'baz'];
9
}
9
void jump() {
9
// classes extending Animal
8
static const wheelCount = 4;

7
/*
8
};

8
/*
9
const ages = [20, 30, 44];
10
// after instantiating an object of type Cat, we can
10
}
10
void jump();
9
const Car();

8
so this code is invalid because
9
// this is not a valid set, and will not compile

9
if you try to change the value of this variable
10
/*
11
// invoke the "run()" function on it
11
// but this one starts with an underscore meaning
11
}
10
}

9
foo is a compile-time constant
10
const names = {

10
after it has been assigned to for the first
11
this grabs the values inside both "names" and
12
void test() {
12
// that it's part of the private interface of this class
12
class Cat extends Animal {
11
void test() {

10
*/
11
'foo',

11
time, you will receive a compilation error
12
"ages" and flattens them inside the new list
12
'foo' // this is not allowed
13
final cat = Cat();
13
void _somethingSecret() {
13
// as shown here
12
// as shown here

11 foo = foo + 'Bar'; // this will not compile 12


*/
13
*/

13 } 14
cat.run();
14
}
14
@override void jump() { }
13
print(Car.wheelCount);

13 age = age + 30; // this will not compile 14 const all = [...names, ...ages]; // List<Object> 15 } 15 } 15 } 14 }

Maps Functions Arguments Operators Mixins If and Else For Loops Assertion
Maps are key value containers, meaning that for a value to be stored inside the map A function is a group of lines of code, or even a single line of code, that has a name, Arguments are values that are passed to functions in order to give them more Operators are special functions whose names are symbols. Operators can be prefix, Mixins are reusable pieces of code that can be “dragged into” other classes. A class If ane else facilitate conditional programming in Dart. The “if” statement allows you to For loops are used to create, well, loops. A loop is used when you need to repeat a task Assertion is a way for a programmer to “assert” a condition and expect a specific
you need to associate a key to it. The key is then used to retrieve the value. A map or and optionally a return value and arguments. Functions are used for giving contextual information and context as how they should perform their tasks. An argument might infix or suffix meaning that they can perform operations on data by being specified can inherit code from multiple mixins at the same time and in that sense mixins can be check for a condition, and execute code based on whether that condition is true or N number of times. There are two types of for loops: the first type is the traditional type result from it. It’s a defensive way of programming your Dart code. Assertions are
hash map or dictionary as it may be named in other languages is usually used to store meanings to code that are related to each other which perform a specific task. For have a data type and must have a name that the function internally can use in order to before that data (prefix), between two pieces of data (infix) or by appearing after an regarded as allowing multiple inheritance in Dart where a class can use multiple mixins false. If the condition is not met according to your criteria, you can provide an “else” where you have a counter that increments or decrements as you program it or you can usually used in places where you are expecting a certain condition that is out of your
structured data. Keys of the map need to be hashable and unique. In Dart you can instance, a Person object might have a function called “run” that performs the running refer to that argument. An argument can optionally specify whether it is a required object (suffix). Dart comes with its own built-in operators but you are allowed to define at the same time. However in Dart, a class can only inherit functionality from one statement that will be executed instead. Together these two language constructs are have a for loop that iterates over an iterable and returns only the objects inside the control to be true/false, and you want to ensure that the program crashes early if your
retrieve a value by key, or just retrieve all the keys or all the values separately. task for that particular person object. argument or not. Required arguments are prefixed with the “required” keyword. your own operators for existing and new objects. super-class at a time. facilitate the basics of conditional programming in Dart. iterable without an explicit counter. assumption turns out not to be met.

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

maps - dart.de functions - dart.de parameters - dart.de A tour of the Dart language (Operators) - dart.de Dart: What are mixins? - Mediu If and Else - dart.de For Loops - dart.de Assert - dart.de
Dart Programming - Map - Tutorialspoin the main function - dart.de Dart: Optional Function Parameters - aistZ Dart Programming - Operators - Tutorialspoin Adding features to a class: mixins - dart.de Dart Programming - If Else Statement - Tutorialspoin Dart Programming - for Loop - Tutorialspoin Dart Assert Statement - W3Schools | W3Add
Dart Map - zetcode.co anonymous functions - dart.de Function arguments - Flutter by exampl Dart Operators - W3School Introduction to Mixins in Dart - DigitalOcea Syntax of Dart If Statement - Tutorial Kar Dart Loops - W3Schools | W3Add Assert Statements in Dart - GeeksforGeek
Maps in dart - Jay Till Dart Programming - Functions - Tutorialspoin Dart Optional Parameters - W3School Operators in Dart - GeeksforGeek Dart Mixins - techLo Dart if else if Statement - W3Schools | W3Add Understanding Loops and Iteration in Dart - Section.i assert statement in Dart explanation with example - codevscolo
Dart/Flutter Map, HashMap Tutorial - Bezkoder Dart function - working with functions in Dart - etCode
Z Optional Named Parameter - Tutorialspoint Dart Operators - Javatpoint Mixins in Dart Programming - Tutorialspoint Dart if else-if Statement - Javatpoint Dart Loops - Javatpoint Assert condition, in Dart - Programming Idioms

Examples Examples Examples Examples Examples Examples Examples Examples


1
// here are two mixing that provide two different

1
// int this example we are using the if and else-if

2
// functions to whoever uses them using the "with" keyword
1
const valueToPrint = 'Foo Bar';

1
/*
1
/*
2
// plus else on its own to describe a person based
1
void allowOnlyOneTeenager(List<int> ages) {

3
mixin CanJump {
2
// here is a C-style for-loop using a counter

2
person nfo in this case is a Map<Object, Object>
2
here is an example of a person class with an empty
1
/*
1
var foo = 10;
3
// on her age, you can chain your if and if-else
2
// in this function we are tasked with printing

I
4
void jump() { print('Jumping...');}
3
// variable that increments, using the ++ notation

3
where keys are of type Object and the values
3
function called run, that returns no values (denoted
2
this function takes in two arguments of type int and
2
/* this is an example of an infix operator that
4
// statements as much as you want
3
// the ages that are placed inside the "ages" argument

5
}
4
// in every loop iteration

4
are of type Object as well.
4
by the void result type) and takes in an argument
3
it returns the result of adding them together, and the
3
sits between two values */
5
void printPerson nfoBasedOn({required int age}) {
4
// but we also need to make sure there is maximu
6
mixin CanRun {
5
for (var i = 0; i < 5; i++) {

I m

5
*/
5
of type double that denotes the speed in kilometers
4
result is of the same data type as the incoming arguments
4
final fooPlusTwo = foo + 2; // fooPlusTwo = 12
6
if (age < 13) {
5
// 1 teen between the ages 13 and 18 inside this list

7
void run() { print('Running'); }
6
print(' teration $i, value = $valueToPrint');

7
print('Child');
6
final teenagers = ages

6
final person nfo = {

I 6
by which the given person should run when this
5
*/
5
/* this is a prefix operator that first adds 1
8
}
7
}

7
'name': 'Foo bar',
7
function is invoked
6
int add(int value1, int value2) {
6
to "foo", and then assigns the result to "bar" */
8
} else if (age >= 13 && age < 18) {
7
.where((age) => age >= 13 && age < 18);

9
// this class uses the mixins and can invoke
8
const ages = [10, 20, 30];

8
'age': 20,
8
*/
7
return value1 + value2;
7
final bar = ++foo;
9
print('Teenager');
8
// so we can make an assertion here to ensure that

10
// the jump() and the run() functions
9
// and here is a modern for-loop that doesn't

9
'address': 'dummy',
9
class Person {
8
}
8
/* this is an example of a suffix operator that
10
} else if (age >= 18) {
9
// our application crashes as we develop it should we

11
class Human with CanJump, CanRun {
10
// use a counter, and instead iterates over

10
10: 20,
10
void run(double speed n ilometers) {
9

9
first assigns the value of foo to baz and then
11
print('Adult');
10
// provide an invalid list of ages to this function

I K
12
void test() {
11
// an iterable using just a "for" keyword

11
};
11
// perform the running task here
10
// another example of a function, a short one!
10
adds 1 to foo */
12
} else {
11
assert(teenagers.length <= 1);

13
jump();
12
for (final age in ages) {

12
// access the name out of person nfo with its key
12
}
11 int subtract(int value1, int value2) => value1 - value2; 11 final baz = foo++; 13
print('What are you?!');
12
print(ages);

I
14
run();
13
print(age);

13 final name = person nfo['name']; 13 } 14


}
13 }
I
15
}
14 }
15 }
16 }

Null Nullability Enums Extensions Factory Constructors Await Object


Null is a special value in Dart. It’s not zero, it’s an absence of a value in essence. Null, Nullability is the ability for a value to either be present or not. The absence of a value An enum is a container for related values, all being assigned a name. Enums are also Extensions in Dart are ways for you to add new functionality to existing code. Imagine Factory constructors are a way to enable a class to be initialized/constructured using Constructors are special functions inside the class that set up the class instance Using the “await” keyword in Dart you can wait on asynchronous operations and grab An object is an instance of a class. Object in itself in Dart has a special meaning in that
or as it is written in Dart, “null”, can be assigned to any value that can contain inside a variable or a return value of a function is it’s quality of being nullable, and for called enumerations and they are defined using the “enum” keyword. Enum cases as a class that is part of the Dart SDK. This class is already packed with functionality and logic that might not always return a new instance of the class, rather, it’s a way for a members. In other words, constructors set up the instance of the class so that it’s their result before continuing with your work. Await is always used together with Object is in fact a class of its own and every other class in Dart implicitly extends this
optionals. Dart has support for the concept of nullability and for a value to be null it the compiler to support nullable values is its ability to support nullability. The modern they are known are the values that are categorized under the enumeration and they are you may not be comfortable with going inside this class and changing its class to make special calculations, such as returning an instance from a cache, or ready for consumption. For instance, you might decide to throw an exception inside a functions marked as “async”. You cannot await on a function that synchronously class. So all your custom Dart classes have Object as their parent class without you
has to be nullable. A value of type “String” cannot contain “null”, but a value of type Dart compiler has support for nullability and in fact it is encouraged that programmers usually all written in lower-case letters and separated by commas. An enum can implementation, even though you technically could. Using extensions you can add initializing instance variables of the class with given data, that cannot otherwise be class called AdultPerson, if the given age for that person is lower than 18. You can returns its value. Using “await” substantially increases productivity in working with having to extend the Object class manually. The Dart SDK implements some handy
“String?” can since the question mark denotes support for nullability. adopt this new way of programming in Dart. contain one or multiple values although an enum with 1 value is rare to find. functionality to existing bits of code without modifying their original implementation. done inside the constructor of the class. have classes without constructors as well. futures and streams in Dart functions on Object such as equality with == and “toString()” so you don’t have to!

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

Null - dart.de Sound null safety - dart.de Enumerated Types - dart.de Extension Methods - dart.de Factory Constructors - dart.de Constructors - dart.de Asynchrony support - dart.de Object Class - dart.de
Sound null safety - dart.de Understanding null safety - dart.de Dart Programming - Enumeration - Tutorialspoin Dart Extension Methods - QuickBird Studios Blo Factory Constructor in Dart - Mediu Using constructors - dart.de Asynchronous programming codelab - dart.de Dart Classes and Object - Javatpoin
Null-aware Operators in Dart - Mediu Unsound null safety - dart.de Dart Enums - techLo Dart Extension Methods Fundamentals - Mediu Understanding Factory constructor code example - newbedev.co Constant Constructors - dart.de Future in dart: When to use async, await, and then - dev.t Dart Object - W3Schools | W3Add
The worst mistake of computer science - Lucidchar Migrating to null safety - dart.de Data Enumeration in Dart - GeeksforGeek Dart Extensions - techLo Factory Constructor In Dart - learndartprogramming.co Using parameterized types with constructors - dart.de Using await async in Dart - GeeksforGeek Object class - dart:core library - Flutter API doc
The Meaning of Null in Databases and Programming - arxiv.org Null safety codelab - dart.dev Flutter & Dart: ENUM Example - Kindacode Dart extension methods - YouTube Exploring the 3 Types of Constructors in Dart - betterprogramming Constructors in Dart - GeeksforGeeks Async/Await - Flutter in Focus - YouTube Dart Programming - Object - Tutorialspoint

Examples Examples Examples Examples Examples Examples Examples Examples


1
// this value is denoted as an optional integer using
1
// this is a simple class describing a Person
1
class Number {
1
// this function produces the integer value of 10

1
// here is a simple enumeration in Dart that
1
// this is a Person class that explicitly extends the

2
// the question mark, meaning that at any point
2
// who at the very least has a name
2
// this factory method allows anybody to
1
// here is an Adult class whose only responsibility
2
// after waiting 3 seconds. This is an asynchronous

1
// this function's argument named "value" is marked
2
// has only two cases, namely "dog" and "cat"
2
// Object class. You should never need to do this

3
// in the execution of this code-scope, it's value
3
class Person {
3
// instantiate a Number class using an Object value
2
// for now is to accept a person's age and store it
3
// function, as denoted by its return type of Future

2
// with square brackets meaning that this parameter
3
enum Animal ind { dog, cat }
3
// though since all classes implicitly extend Object

4
// can be set to null
4
final String name;
4
// but underneath, this factory constructor creates
3
// inside its "age" member
4
Future<int> produceValueAfter3Seconds() {

3
// is now an optional positional parameter, hence
4
// and in this abstract class we dictate that all
4
class Person extends Object { }

5
int? value;
5
const Person({required this.name});
5
// an instance of the nteger class should the
4
class Adult {
5
return Future.delayed(Duration(seconds: 3), () => 10);

4
// its value can be null
5
// subclasses should have a getter called kind
5
// this is another Person class that doesn't extend

6
if (value == null) {
6
}
6
// given value be of type int
5
final int age;
6
}

5
void add10ToValue([int? value]) {
6
// of our Animal ind enum type
6
// Object; this is what you need to do for your

7
// using a simple if statement you can test
7
// using an extension called Description, on
7
factory Number.from(Object value) {
6
// inside the constructor for this class we are
7
// this function is marked as "async" meaning that

6
// and given that "value" can be null, using the
7
abstract class Animal {
7
// own classes as well

8
// for the nullability of this value
8
// Person instances, we can extend every Person
8
if (value is int) {
7
// taking precautions to ensure that the given
8
// inside this function you can use the "await"

7
// ?? operator we substitute "value" with 0
8
Animal ind get kind;
8
class OtherPerson { }

9
print('This value is null');
9
// instance to have a getter called "description"
9
return nteger(value);
8
// age is in fact more than or equal to 18 and
9
// keyword to wait on the result of other async functions

8
// should "value" be 0, and then we add 10
9
}
9
// and both classes have inherited the toString()

10
} else {
10
// that prints information about that instance
10
} else { throw ' nvalid value'; }
9
// should that not be the case, our application
10
void waitOnValue() async {

9
// to the entire result and print it out
10
class Dog extends Animal {
10
// function from Object

11
// and using "else" you can make sure this is
11
extension Description on Person {
11
}
10
// will stop execution and crash, ensuring we
11
// here we "await" the result of the function above

10
final valuePlus10 = (value ?? 0) + 10;
11
// and here in the Dog class we override that and
11
void test() {

12
// variable is not null
12
String get description => 'Person, name = $name';
12
}
11
// won't pass invalid values to this constructor
12
// using the await keyword

11
print(valuePlus10);
12
// return Animal ind.dog
12
print(Person().toString());

13
final result = value + 2;
13
}
13
class nteger implements Number {
12
const Adult({required this.age}) : assert(age >= 18);
13
final value10 = await produceValueAfter3Seconds();

12 } 13
@override Animal ind get kind => Animal ind.dog;
13
print(OtherPerson().toString());

14
print(result);
14
const person = Person(name: 'Foo Bar');
14
const nteger(int value);
13 } 14
print(value10);

K K

14 } 14 }
I

15 } 15 print(person.description); 15 } 15 }

Anonymous Functions Nested Functions Type Testing Logical Operators Cascade Notation Bitwise Operators Shift Operators Class Members
Anonymous functions are just like normal functions, but they have no name. They are Many programming languages including Dart allow you to nest functions inside other Type testing in Dart is the process of dynamically checking the type of an object at run- Logical operators in Dart are “&&”, “||” and “!”, where “&&” ensures both sides of the This is an operator that allows you to perform methods or assign values to member Everything in computers is constructed out of bits. At least the modern computers that Shift operators, just like bitwise operators, allow you to manipulate bits at a low level A class member is, as its name implies, a variable of a class. Every variable has a
not assigned to variables, since assinging an anonymous function to a variable gives it functions. These are called nested functions. They are useful for giving a name and a time. There are 3 operators that allow you to type-test objects in Dart and those are operator are “true”, the “||” ensures that at least one of operators on the sides is true variables of a class instance without you having to perform dot notation for every we work with all work with bits. A bit is a value that can either be 0 or 1 but not both. inside objects. There are 3 main shift operators in Dart and those are “>>” which shifts lexical scope and a member variable’s lexical scope is inside its defining class and
a name (the name of the variable), hence defeating the purpose. Anonymous functions scope to a reusable piece of functionality that doesn’t necessarily belong to the outer “as” and “is” and “is!”. The “as” operator allows you to type-cast an object to another and the “!” operator inverts the condition provided to the operator. Together these three access operation. Using the cascade notation and its brethren operator null-shorting Any data type in Dart is constructed out of a series of bits that either contain the exact a value to the right, “<<” that shifts the value to the left and the “>>>” which shifts a depending on access levels, perhaps even descendants of the parent class. Member
are usually passed to other functions that expect a callback, where the anonymous scope of the function (such as its containing class), rather they are scoped to another type at run-time and perform various operators on it while the “is” operator becomes operators are the basic blocks of conditions in Dart and almost every other cascade notation “?..” you can construct complication objects without the need to data behind the value or they contain a pointer to where the data is stored. Bitwise value to the right as an unsigned value. Together these operators allow you to shift variables are used to store information that is important to their class instance, such
function is used as the callback to receive updates. function. “true” if the given object is of a certain type and “is!” becomes true if the reverse is true. programming language available right now. repeat the name of the variable before every dot notation. operators allow you to manipulate these bits at a low level. right and left your integers. as a Person class having a “firstName” and “lastName” member variables.

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

Anonymous Functions - dart.de Lexical scope - dart.de Type test operators - dart.de Logical operators - dart.de Cascade notation - dart.de Bitwise and shift operators - dart.de Bitwise and shift operators - dart.de Using class members - dart.de
Dart - Anonymous Functions - GeeksforGeek How to create a nested function in Dart - Educative.i Dart Type test operators - W3Schools | W3Add Dart Programming - Operators - Tutorialspoin Dart Cascade notation (..) - W3Schools | W3Add Dart Bitwise operators - W3Schools | W3Add Dart Operators - Javatpoin Dart Programming - Classes - Tutorialspoin
Dart Anonymous Function - Javatpoin dart Tutorial => Function scoping - riptutorial.co Type Test Operators - Flutter by Exampl Dart Logical operators - W3Schools | W3Add What is Dart cascade notation? - Educative.i Bitwise and Shift Operators in Dart - learndartprogrammin Bitwise and Shift Operators - Flutter by Exampl Creating Objects and Classes in Dart and Flutter - dart.academ
Dart Anonymous Functions - W3Schools | W3Add Nested function - Wikipedi Type test operators in Dart - learndartprogramming.co Operators in Dart - GeeksforGeek Method Cascades in Dart - dartlang.or Dart Operators - Javatpoin Bitwise and Shift Operators - educative.i Instance and class methods in Dart - GeeksforGeek
Anonymous function in Dart Programming - Tutorialspoint Learning Functions for Dart - Seth Ladd's Blog Dart Programming - Type test Operators - Tutorialspoint Logical Operators - Flutter by Example Cascade notation - Flutter by Example Bitwise and Shift Operators - Flutter by Example Shift operator - Wikipedia dart Tutorial => Members - riptutorial.com

Examples Examples Examples Examples Examples Examples Examples Examples


1
const names = ['Foo', 'Bar', 'Baz', 'Foo'];

1
void describe(Object obj) {
1
class Person {
1
// the hexadecimal value of 0x01 is equivalent to the

2
// here we have a function that prints the list of

1
const names = ['Foo', 'Bar', 'Baz', 'Foo Bar'];
2
// using the "is" keyword you can test to see if
2
String firstName = '';
2
// binary value of 0001, hence shifting it to the left

3
// "names" with their indices
1
final foo = true;
1
class Person {

2
void printNamesWith3Letters() {
3
// a givne object is of a specific type
3
String lastName = '';
3
// 1 place will change the vlaue to 0010, filling the

4
void printOrderedNames() {
2
final bar = false;
1
final value1 = 0x01;
2
// here is a class that contains two member variables

3
names
4
if (obj is int) {
4
}
4
// right side with a zero. 0010 in base-10 is 2

5
// inside this function we have a helper, nested
3
if (foo && bar) {
2
final value2 = 0x02;
3
// namely firstName and lastName, these two variables

4
// here we are iterating through all the values
5
print('This is an integer');
5
void test t() {
5
print(0x01 << 1);

6
// function that produces a String describing
4
// this block of code will be executed only if
3
// value3 will be 0001 AND 0010 = 0000 (0)
4
// or properties as they are sometimes called are

5
// inside the "names" constant list, and using
6
}
6
// using the cascade notation .. we can assign
6
// the hexadecimal value of 0x02 is equal to 0010 in

7
// the index of each name in the list of names
5
// both foo and bar are equal to true
4
final value3 = value1 & value2;
5
// useful for this class, since the getter fullName

6
// the "where" function, we pass an anonymous
7
// here we are making an assumption about the
7
// values to both firstName and lastName
7
// binary and shifting it to the left 2 places makes

8
String prefixFor(int index) =>
6
} else if (foo || bar) {
5
// value4 will be 0001 OR 0010 = 0011 (3)
6
// down below is concatenating them in order to

7
// function that calculates which names have
8
// object being a String, if not, the app crashes
8
// properties of Person without having to
8
// it equal to 1000, which is 8 in base-10

9
'Value ${index + 1} = ';
7
// while this block of code will be executed
6
final value4 = value1 | value2;
7
// calculate the person's full name

8
// exactly 3 letters in the 9
print((obj as String).length);
9
// repeat the person variable name beforehand
9
print(0x02 << 2);

10
// then we create an indexed list of names and
8
// if either foo or bar is true
7
// value5 will be 0001 XOR 0010 = 0011 (3)
8
String firstName;

9
.where((name) => name.length == 3)
10
// with "is!" we make sure that the given object
10
final person = Person()
10
// you can shift your values to the left and right

11
// iterate through the 9
} else if (foo && !bar) {
8
final value5 = value1 ^ value2;
9
String lastName;

10
// then for every name that has exactly 3 letters
11
// is *not* of a specific type, here, not a double
11
..firstName = 'Foo'
11
// as much as you want, but shifting a value to

12
names.asMap().forEach((index, value) {
10
// finally, this block of code will be executed
9
// value6 will be ~0001 = 1110 (-2 integer)
10
Person(this.firstName, this.lastName);

11
// we invoke the print function
12
if (obj is! double) {
12
..lastName = 'Bar';
12
// the left loses 1 binary value from the left

13
final prefix = prefixFor(index);
11
// if foo is true and bar is not true (false)
10 final value6 = ~value1; 11
String get fullName => '$firstName $lastName';

12
.forEach(print);
13
print('This is not a double');
13
print(person.firstName);
13
// with each shift, similar to how shifting a

14
print('$prefix = $value');
12 } 12 }
13 } 14
}
14
print(person.lastName);
14
// value to the right loses one binary value fro
15
});

15 } 15 } 15 // the right with each shift


16 }

Extension Methods Generics Generic Classes Generic Functions Generic Typedefs Generators Main Function Late Variables
Extension methods are methods that are added to existing classes outside the original In Dart, you can use generics to avoid using specific data types in your code. For A generic class is that which takes in one or more so-called generic types, usually Generic functions, just like generic classes, work with data types that are not known at Type definitions in Dart allow the programmer to map a data type to another or even by Generators in Dart are used to lazily create a sequence of values. A lazy sequence is an The main function is the entrance to your application. You never call the main function A late variable is a variable whose value will be determined at a later stage compared
class declaration. Extensions are usually used to separate pieces of code that might instance, you can write a class that allows you to perform arithmetic operations on an annotated with single letters such as T, G, E, etc, and allows the consumer of the public the time of writing them. For instance, a function that adds two integers can be made a assigning a name to a function of a specific return value and parameters. A generic iterable whereas its counterpart is a list that is not created lazily. A generator is a manually. Instead, when you run your Dart application, the Dart runtime will call this to when it was defined. For instance, if you have a stream controller in Dart which you
not otherwise belong together. If you see that your class is getting bigger and difficult integer but soon you will realize that the operations might not only be applicable to interface of the API to call methods and getters and setters inside the class as if the generic function by allowing any number to be added to each other and returned. Such typedef on the other hand leaves either its arguments or return data open for function that allows you to return an iterable list of values, such as fibonacci numbers, function for you. Main functions are available in almost every other language and cannot allocate immediately inside your class initializer, you may decide to flag it as
to manage all the code within it, it is a good idea to break the functionality of that class integers, but also on doubles or even other similar numeric data types. In that case, class was written for the specific data type the consumer is expecting. Generic classes a function will then be made specialized by the compiler at compile-time into specific interpretation by the compiler by making those generic so that more than one data without you having to calculate the entire sequence at once. Instead you can calculate runtime as well. In a Dart application your main function usually accepts parameters “late”, to indicate that its value will be determined at a later stage than its definition,
down into separatea areas and extensions. you might want to use generics to avoid having to re-coding your implementation. help remove boiler-plate and repeated code. data types as used by the programmer. type can be passed to the function or returned by it. the values and return those values with yield as the caller consumes them. from the caller as well which you can use to process the user input. usually inside the constructor of your class.

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

Extension methods - dart.de Generics - dart.de Generics - dart.de Generics - dart.de Dart Typedef - W3Schools | W3Add Generators - dart.de The main() function - dart.de Late variables - dart.de
Extension methods in Dart - wilsonwilson.de Generics in Dart and Flutter - dart.academ Working with generic types in Dart - mediu Generic methods in Dart - Educative.i Explore TypeDef In Dart & Fluter - Mediu Dart Generators - techLo Dart - main() Function - GeeksforGeek Late variables in dart and lazy initialization - dev.t
Fluttering Dart: Extension Methods | by Constantin Sta Dart Generics - techLo Generics in Dart explanation with example - CodeVsColo Dart 1.21: Generic Method Synta Take advantage of type aliases in Dar Generators in Dart - GeeksforGeek Dart main() Function - W3Schools | W3Add Flutter: Lazy instantiation with the `late` keywor
Dart Extensions: Full Introduction and Practical Use Case Dart Programming - Generics - Tutorialspoin Dart - Generics - GeeksforGeek Dart - Generics - GeeksforGeek Creating an instance of a generic type in DAR Dart Generators - W3Schools | W3Add Dart main() function - Javatpoin Dart Late Modifier - YouTub
Use of Dart extension Methods in existing APIs Class Dart Generics - Javatpoint Generics - Dart - Metanit Working with generic types in Dart - medium Prototype Syntax for Generic Methods Dart Generators & Callable Class In Flutter - Medium Dart Programming - Syntax - Tutorialspoint Dart Null Safety: The Ultimate Guide to Non-Nullable Types

Examples Examples Examples Examples Examples Examples Examples Examples


1
// here we have a class that accepts a first name

1
// here we have a class called Person that exposes
1
// a generic typedef is just like a normal type-def
1
// a generator is a special function in Dart that is
2
// and a last name, but it's fullName member variable

1
// here we have a class named Stack that works

2
// two member variables first name and last name
1
// generic classes define their own generic types using
1
// here is an example of a generic function that
2
// with one exception; that being the typedef accepts
2
// marked with an iterable/stream as its return value
3
// is marked as being a "late" variable, meaning that

2
// in such a way that generic values of type T,

3
class Person {
2
// notations such as T or E. t's completely up to you
2
// defines a generic type called T that has to extend
3
// one or more generic types, denoted usually with
3
// plus a sync* or async* as its decorator, denoting
1
void main(List<String> args) {
4
// we are promising the compiler that this variable

3
// a type we have just named T for the sake of

4
String firstName;
3
// how you alias your generic types
3
// the class "num", and the function is called "plus".
4
// single letters such as T and E. The generic
4
// synchronous or asynchronous generators in that order
2
// this is the main function of a command-line
5
// will in fact be initialized and set to a valid String

4
// simplicity, can be stored in a first-in-last-out

5
String lastName;
4
class NumberStorage<T extends num> {
4
// all this function does is really just adds two
5
// type is then used inside either the return value of
5
terable<int> fromZero({required int upTo}) sync* {
3
// utility written with Dart. Because of this
6
// instance before we use it.

5
// fashion with the push and pop functions

6
Person(this.firstName, this.lastName);
5
final List<T> _list = [];
5
// values namely lhs and rhs and returns the result but
6
// the typedef and/or its arguments
6
// this function simply creates a loop that goes fro 4
// reason it accepts a list of String objects
7
class Person {

6
class Stack<T> {

7
}
6
// then we have a function that can store a generic
6
// it does so using a generic way, in that it takes
7
typedef OnPressedWithValue<T> = void Function(T value);
7
// 0 and up to, but not including, the value passed
5
// representing parameters passed to this utility
8
final String firstName;

7
final List<T> _values = [];

8
// and here we are creating an extension on the
7
// value of the same T type as the class defines
7
// in parameters of type T and returns the same type T
8
// and here is an example of a class that uses our
8
// to it as "upTo"
6
// from the command line. The main function for
9
final String lastName;

8
// the push function accepts values of type T

9
// same class using which we expose a getter called
8
void store(T value) => _list.add(value);
8
T plus<T extends num>(T lhs, T rhs) {
9
// generic typedef
9
for (var i = 0; i < upTo; i++) {
7
// most Flutter apps however uses no arguments
10
late final String fullName;

9
void push(T value) => _values.insert(0, value);

10
// fullName using which we can retrieve the person's
9
// and we expose a getter called "sum" that can
9
// the return value is then type-cast to T in order
10
class MyButton<T> {
10
// and for every value in the loop it uses the
8
// and is simply named "main" with a void return
11
Person(this.firstName, this.lastName);

10
// and the pop function returns values of

11
// full name
10
// collect the sum of all values inside our _list
10
// to make the compiler happy!
11
T value;
11
// "yield" keyword to return its value in the result
9
// value and no sync or async decorators
12
}

11
// type T too

12
extension FullName on Person {
11
T get sum => _list.reduce((lhs, rhs) => lhs + rhs as T);
11
return (lhs + rhs) as T;
12
final OnPressedWithValue<T> onPressed;
12
yield i;
10 } 13
final person = Person('foo', 'bar');

12
T? pop() => _values.isNotEmpty ? _values.removeAt(0) null;

String get fullName => '$firstName $lastName';


} } MyButton(this.value, this.onPressed);
}
14
// however here we crash the program by accessing

:
13
12 12 13
13

13 } 15
// "fullName" before it is initialized

14 } 14 } 14 }
16 print(person.fullName);

Ternary Operator Arithmetic Operators Assignment Operators Collection If Collection For Spread Operators Break and Continue Default Values
The ternary operator in Dart, like many other languages, is a shorthand for an if-else Arithmetic operators are those that usually work on numeric types to allow you to add, Dart has two assignment operators. The first one is the normal “=” operator that The collection-if statement allows you to check for a condition, right inside the creation The collection-for statement in Dart allows you to loop over a collection and output Spread operators in Dart allow you to “spread”, or expand and existing collection into a Both the break and the continue keywords allow you to control the flow inside a loop. Every variable in Dart can have a default value. A default value is a value that you
statement that usually becomes longer if written with an if-else statement. The ternary subtract, multiply and divide those values. However, arithmetic operators, as their assigns the value to its right, to the variable to its left. The other one is the “??=” of a collection, such as a list or a map, and based on that condition, insert new values values, that will then be placed inside a new collection, while you are creating the new one without you having to iterate over the said collection. The spread operator is The “break” keyword as its name implies allow you to break out of a loop should a assign to a variable in order to initialize it. Not all variables have a default value. For
operator is in fact the combination of a question mark “?” and a colon “:” where the name suggests, are operators, and can be used by other data types as well, such as operator that works with nullable values to its left and assings the value to its right to into the collection. This is a very useful feature that helps you in creating your collection in question! If you had two lists of names, and wanted to compile 1 list with written as three dots next to each other like so “...” and a null-aware spread operator is certain condition be met. It’s useful when trying to find a specific value inside a loop. instance, a late variable is a type of variable that doesn’t have a default value to start
value after the question mark is to be consumed if the condition is met and the value String. Dart also has support for the “~/” operator that is a division operator which the nullable value to its left, if the value to the left is null. They are both defined at the collections based on conditionals. The syntax is the same as a normal if statement all names that start with the letter B, you can use collection-for in order to iterate over written with three dots followed by a question mark like so “...?” and allows you to The “continue” keyword allows you skip the current iteration of the loop and go to the with, but will be assigned a value later on in its lifetime. Default values are necessary
after the colon to be used if the condition is not met. returns an integer plus the modulo arithmetic operator “%”. core of Dart so you don’t have to import anything in order to use them. usually without the curly brackets around the value of the condition itself. both lists and put their relevant values inside the final collection. spread a collection into a new one should the collection to the right not be null. next iteration inside the same loop should a condition be met. for constants as they need to be initialized with a value.

Further reading Further reading Further reading Further reading Further reading Further reading Further reading Further reading

Ternary Operator in C Explained - freeCodeCam Arithmetic operators - dart.de Assignment operators - dart.de Collection operators - dart.de Collection operators - dart.de Spread opreator - dart.de Break and continue - dart.de Default value - dart.de
Ternary Operator In Java | Baeldun Operators in Dart - GeeksforGeek Assignment operators in Dart Programming - Tutorialspoin Collection if, collection for, spreads and Copying - YouTub Iterable collections - dart.de Spread Collections - dart-lang/language - GitHu Dart Programming - continue Statement - Tutorialspoin Dart Programming - Variables - Tutorialspoin
C++ Short Hand If Else (Ternary Operator) - W3School Dart Arithmetic operators - W3Schools | W3Add Dart Assignment operators - W3Schools | W3Add Dart Features For Better Code: Spreads, Collection-If - YouTub Exploring collections in Dart - Mediu flutter dart spread operator code example | Newbede Dart - Loop Control Statements (Break and Continue Dart Variables - W3Schools | W3Add
Ternary Operator - Coding Gam Flutter Dart List of All Arithmetic Operators with Example Tutoria Assignment Operators - flutterbyexampl Exploring Dart Collection Types - dev.t Dart - Collections - GeeksforGeek Dart spread operator - I should go to slee Dart Continue statement - W3Schools | W3Add Dart Variable - Javatpoin
What is a Ternary Operator? - Computer Hope operators, expressions, precedence, associativity in Dart Assignment and compound assignment operators in Dart Dart/Flutter List Tutorial with Examples - BezKoder Dart Programming - Collection - Tutorialspoint Spread operator & Null-aware operator on Lists - Morioh Dart continue Statement Tutorial With Examples - FlutterRDart Dart - Variables - GeeksforGeeks

Examples Examples Examples Examples Examples Examples Examples Examples


1
class Person {
1
// here we have a valid list of strings
1
const names = ['Foo', 'Bar', 'Baz'];

1
// arithmetic operators are defined at the heart of
1
// the assignment operator shown here sets the

1
// in this extension we are exposing a getter called
2
final String firstName;
2
final names = ['Foo', 'Bar', 'Foo'];
2
String? foo;

2
// Dart allowing you to perform operations such as
2
// value of the 'name' constant to 'Foo'. This is
1
const names = ['Barbra', 'Bob'];
1
const names = ['Foo', 'Bar', 'Baz'];

2
// "isOr sNot" on every value of type "bool" and this
3
final String lastName;
3
// and a list of strings that is null at the
3
for (final name in names) {

3
// addition and multiplication between numeric
3
// what the assignment operator does. t takes the
2
// in this example we are going to loop over a list

3
// allows us to call "isOr sNot" on any boolean value

I 2
const otherNames = ['Foo', 'Bar', 'Baz'];
4
// point of its creation
4
if (name.isEmpty) {

I
4
// values such as 1 or 1.0, 3.0 etc.
4
// value from the right hand side and assigns it
4

3
// of names and find the one that has the most amount

4
// in order to get the string "is" or "is not" depending
3
// in this example we have two lists of names and we
5
List<String>? nullNames;
5
// although not necessary, we are using the continue

5
const value1 = 1;
5
// to the variable on the left
5
const Person(this.firstName, this.lastName);
4
// of characters, aka, the longest, and place it inside

4
// want to use the collection-for statement in order to
// using the ... spread operator, we take all the

5
// on whether the boolean value is true or false

6
const value2 = 2;
6
const name = 'Foo';
6

5
// join the lists. This is just for the purpose of

6
6
// statement here that jumps to the next iteration

5
// the "longestName" variable. n this case we are

6
extension sOr sNot on bool {
the collection-if statement allows you to embed
7
// values inside the "names" variable and place
7
// of this loop should the current name in the list

I
I I
7
// an example of using the addition operator
7
// same here, we take the value of 20 and assign it
7
// 6
// setting the default value of this variable to an

7
String get isOr sNot => this ? 'is' : 'is not';
6
// demonstration on how to use the collection-for statement
8
// them inside the "uniqueNames" set. Remember that a
8
// be empty, meaning that it's of 0 length

I
8
const plus = value1 + value2;
8
// to the 'age' constant
8
// fully functioning if-statements inside your collection
7
// empty string, so that its length is 0

8
}
7
// since you can achieve the same result in other more
9
// set will remove all duplicate values, meaning that
9
continue;

9
// and using the subtraction operator
9
const age = 20;
9
// creation code; in other words, inside the [] or the
8
String longestName = '';

9
void test t() {
8
// optimal ways. We are then using the for statement right
10
// the second 'Foo' instance will disappear. Then we are
10
}

I
10
const minus = value2 - value1;
10
String? homeAddress;
10
// {} code where you usually create your lists or maps/sets
9
for (final name in names) {

10
// the following will print "is"
9
// inside the collection creation code as you can see
11
// using the ...? operator in order to optionally
11
if (name == 'Foo') {

11
// you can include if-statements in order to determine

11
print(true.isOr sNot);

11
// you can also multiply values using
11
// using the ??= assignment operator you can set the
10
final allNames = [
12
// spread the nullNames list here as well
12
foo = name;

10
if (name.length > longestName.length) {

I
12
// the multiplication operator
12
// value of an optional variable to the left, equal
12
// the result of your collection getters/functions
11
longestName = name;

12
// while this will print "is not"
11
...names,
13
final uniqueNames = {
13
// otherwise as soon as we find 'Foo', we break out

13
const multiply = value1 * value2;
13
// to the value on the right, should the left-hand-side
13

12
}

13
print(false.isOr sNot);
12
for (final name in otherNames) name,
14
...names,
14
break;

I
14
// and of course division is also supported
14
// variable be equal to null
14
List String> names( bool includeLastName = true ) =
< [ ] >

13 }
14 } 13 ];
15
...?nullNames,
15
}

15 const divide = value2 / value1; 15 homeAddress ??= 'Unknown'; 15


firstName, if (includeLastName) lastName ;

[ ]

16 } 16 }; 16 }

You might also like