Dart Examples
Share
Dart Examples
This page lists the examples from every chapter of the Dart tutorial.
Click on an example to open it in our "Try it Yourself" editor.
Click on the button below each list to read the chapter.
Dart Intro
Intro ExplainedDart Get Started
Get Started ExplainedDart Syntax
We used this code to print "Hello World" to the screen
This program has three statements, and Dart runs them in order
Syntax Explained
Dart Output
You put the value you want to show inside the parentheses
Each call prints its value on a new line
Numbers are written without quotes
You can do math inside
Output Explained
print(), and Dart prints the result
To print several pieces of text on one line, join them into one string with the + operator
To put a value inside a string, write a dollar sign $ and then the variable name, or write ${} around a...
stdout belongs to the dart:io library, so you must import it at the top of the file
To start a new line inside a string, use the special character \n
Dart Comments
This example uses a comment before a line of code
This example uses a comment at the end of a line of code
This is called commenting out code
Dart ignores all text between them, even if it covers many lines
You can also use
Comments Explained
/* */ to hide a small part of a line
Code editors show this text when you point at the name, and tools can turn it into web pages
Dart Variables
After you create a variable, you can use its name to get the value
Instead of
Variables Explained
var, you can write the type before the variable name
You can see the type of a value with runtimeType
You can give a variable a new value later in the program
You can create a variable with a type and give it a value later
The first word starts with a small letter, and every word after it starts with a capital letter
Dart final and const
For this, use the
final and const Explained
final keyword instead of var
You can also write the type after final
The const keyword also creates a variable that cannot change
Numbers, strings, true, false, and calculations with other constants are compile-time constants
For example, the current time is only known when the program runs, so it can be final
A final list cannot be replaced with another list, but you can still change the items inside it
Dart Data Types
For example, you can multiply two numbers, but you cannot multiply two names
You can find the type of any value with the
Data Types Explained
runtimeType property
int and double are both numbers, and num can hold either of them
Text is stored as a String, and a yes or no value is stored as a bool
A List keeps values in order, a Set keeps only unique values, and a Map stores pairs of keys and values
A variable of type dynamic or Object can hold a value of any type
Dart Numbers
An
Numbers Explained
int is a whole number, positive or negative, without decimals
A double is a number with decimals
A double can also be written in scientific notation, with an e that means "times 10 to the power of"
A variable of type num can hold an int or a double
To get a whole number result, use ~/ instead
You use them with a dot after the number or the variable
Use toStringAsFixed() to show a number with a fixed number of decimals, for example a price
Use int.parse() or double.parse() to turn the text into a number
Dart Strings
In Dart, you write strings inside single quotes or double quotes
You can use single quotes inside a string with double quotes, and double quotes inside a string with...
It puts a special character in the string
To write a string over several lines, use three single quotes
Strings Explained
''' or three double quotes """
In a raw string, a backslash is just a backslash, and escape characters do not work
This is called concatenation
message += ' morning' is a short way to write message = message + ' morning'
The length property gives the number of characters in a string
The first character has index 0, the second has index 1, and so on
Dart String Interpolation
To do this, write a dollar sign
String Interpolation Explained
$ followed by the variable name, inside the string
You can use as many variables as you want in one string
To put an expression inside a string, write it inside ${}
You also need ${} when you use a property or a method of a variable
If you forget the curly brackets, Dart only uses the variable name and prints the rest as normal text
With interpolation, Dart turns the value into text for you
You can also use a raw string, which does no interpolation at all
Interpolation also works in multi-line strings
Dart String Methods
It returns a new value instead
String Methods Explained
contains(), startsWith() and endsWith() return true or false
indexOf() returns the position of the first match, and -1 if there is no match
If you leave out end, you get the rest of the string
replaceAll() replaces every match with another string
split() cuts a string into a list of strings, at every separator
trim() removes spaces at the start and at the end of a string, which is useful for text that a user typed
padLeft() adds characters at the start until the string has the length you ask for
Dart Booleans
A
Booleans Explained
bool value is either true or false
This kind of code is called a boolean expression
You can compare variables, and you can store the answer in a variable
Strings can also be compared with ==
The ! operator turns true into false, and false into true
The if statement runs a block of code only when a boolean is true
Write a comparison instead, so the condition is a boolean
Dart Type Conversion
Use
Type Conversion Explained
double.parse() to convert a string to a decimal number
If the string is not a valid number, they return null, which means "no value"
Use bool.parse() to convert the text 'true' or 'false' to a bool
After that, you can join it with other strings
Use toStringAsFixed() to get a string with a fixed number of decimals
toInt() removes the decimals, it does not round
Use ceil() to round up, and floor() to round down
Use toInt() when you need an int from a num
Dart Null Safety
A
Null Safety Explained
String? can hold a string or null
Inside the if block, Dart knows that the value is not null
The same code also works when the text is not a number
This is called the null assertion operator, and it turns an int? into an int
The ?? operator gives a default value when a value is null
Dart late
The
late Explained
late keyword tells Dart: "This variable will get a value later, before it is used."
A late final variable gets its value later, but only one time
In this example, loadMessage() is a small function that prints a line and returns a string (you will learn...
If the variable is never read, the value is never created
Dart Operators
In the example below, we use the
Operators Explained
+ operator to add two numbers
The operands can be values, variables, or a mix of both
Like in math, multiplication is done before addition
Use parentheses () to calculate a part first
With strings, + joins two strings, and * repeats a string
Comparison operators always give a bool value, true or false
Dart Arithmetic
Arithmetic operators are used to do common math with numbers
The
Arithmetic Explained
/ operator always gives a double, even when both numbers are integers
The result is an int
The % operator gives the remainder, which is what is left over after a division
An even number has a remainder of 0 when you divide it by 2
If one of the operands is a double, the result is also a double
The ++ operator adds 1 to a variable, and the -- operator subtracts 1
The difference matters when you use the result in the same expression
Dart Assignment
The most common one is
Assignment Explained
=, which gives the value on the right to the variable on the left
x += 5 is a short way to write x = x + 5
A list of all assignment operators
It adds text to the end of a string
Use a double variable with /=, or use ~/= for integer division
The ??= operator gives a value to a variable only if the variable is null
Dart Comparison
The result of a comparison is always a
Comparison Explained
bool, true or false
You can store the result of a comparison in a bool variable
An int and a double with the same value are equal
The comparison is case-sensitive, so 'Apple' and 'apple' are not equal
It returns a negative number if the first string comes first, 0 if they are equal, and a positive number...
Dart Logical
The
Logical Explained
&& (and) operator returns true only if both sides are true
The || (or) operator returns true if at least one side is true
The ! (not) operator turns true into false, and false into true
Use parentheses to make the order clear
In this example, age > 18 is only checked when age is not null
Dart Type Test
The
Type Test Explained
is operator returns true if a value has a type
It returns true if a value does not have a type
In the example below, toUpperCase() only exists on strings, but we can use it because Dart knows that...
This is called a type cast
Dart Null Operators
The
Null Operators Explained
?? operator gives a default value when the left side is null
The ??= operator gives a variable a value, but only if the variable is null
If the value is null, the result is null, and the program does not stop
You can combine ?. and ?? to get a default value
A list is a group of values in square brackets (you will learn more in the Lists chapter)
The ?.. operator runs the cascade only if the value is not null
Dart Cascade
Without cascades, you must write the variable name again on every line
You write the object one time, and start every operation with
Cascade Explained
..
Here we use a list, a group of values in square brackets (you will learn more in the Lists chapter)
With ..sort(), you get the sorted list back
The whole cascade is skipped when the object is null
Dart If...Else
Here we test if 20 is greater than 18
You can also test variables
Use
If...Else Explained
else to run a block of code when the condition is false
Dart tests the conditions from top to bottom and runs only the first block whose condition is true
You can use as many else if parts as you need
This is called a nested if
You can often write the same check with the logical operator && instead
Instead of writing this
You can simply write
Dart Switch
This example uses the weekday number to print the weekday name
The
Switch Explained
default keyword gives the code to run when no case matches
This lets several values share the same code
You can also put several values in one case with ||, which means "or"
Each case runs as many statements as you need
Dart While Loop
In this example, the loop runs as long as
While Loop Explained
i is less than 5
A while loop can count down too
This example doubles a savings amount until it reaches at least 1000
Note the semicolon ; after the condition
Here the condition i < 5 is false, but the code block still runs one time
A while loop with the same condition does not run at all, so this program prints only "Done"
Dart For Loop
This example prints the numbers 0 to 4
This example prints only the even numbers from 0 to 10
This example counts down from 5 to 1
This example adds the numbers 1 to 100
The inner loop runs fully for each run of the outer loop
The
For Loop Explained
for-in loop goes through every item in a list, one by one
It runs a function for each item in the list
You can also write a small function in place, with the item as its parameter
Dart Break/Continue
This example stops the loop when
Break/Continue Explained
i is equal to 4
A common use of break is to stop searching when you have found what you are looking for
This example skips the value 4
This example prints only the odd numbers, by skipping every even number
Here break stops a loop whose condition is always true
If you do not, the counter never changes, and the loop never ends
The outer loop goes on
Then write break with the label name
Dart Lists
To create a list, write the items in square brackets
Lists Explained
[], separated by commas
A list keeps its items in order, and it can have the same value more than once
You can also write the type yourself, with List<Type>
To create an empty list, write the type before the brackets
The isEmpty and isNotEmpty properties tell if the list has any items
You can create one with List.filled(), which takes the length and a start value for every item
This example adds an item to a final list
Dart Access List Items
To get an item, write the index in square brackets after the list name
The last item always has the index
Access List Items Explained
length - 1
The first and last properties give the first and the last item of a list
The item at the start index is included, but the item at the end index is not
If you leave out the end index, the new list goes to the end of the list
The contains() method returns true if the list has the item, and false if it does not
If the item is not in the list, it returns -1
The lastIndexOf() method works the same way, but it searches from the end
Dart Change List Items
To change the value of an item, assign a new value to its index
The
Change List Items Explained
add() method adds one item to the end of the list
The addAll() method adds all the items of another list to the end
The items after it move one place to the right
The remove() method removes the first item with the given value
Both methods return the item they removed
The test is a small function that gets an item and returns true to remove it
The list still exists, but it is empty
Dart Loop Lists
The easiest way to go through every item in a list is the
Loop Lists Explained
for-in loop
This example adds up all the prices in a list
Start at index 0, and stop before length
With the index, you can also go through the list backwards
The index also lets you change each item in place
The forEach() method runs a function for each item in the list
With forEach() on that map, you get both the index and the item
Dart List Methods
Numbers are sorted from low to high, and strings are sorted alphabetically
Here we compare
List Methods Explained
b with a, to sort from high to low
Use toList() to turn the result into a list
reduce() starts with the first item, and then combines it with each next item
Use fold() when the list can be empty, or when the result has another type than the items
The reversed property gives the items in reverse order
The every() method returns true only if all items pass the test
Dart Sets
You write a set with curly brackets
Sets Explained
{}, and separate the items with commas
You can also write the type yourself
If you put the same value in a set more than once, the set keeps only one copy
The toSet() method turns a list into a set
Dart reads an empty {} as an empty map
To create an empty set, put the item type in angle brackets before the curly brackets, or write the type...
Use contains() to check if an item is in the set
It returns false if the item was already in the set
You can combine two sets in three ways
Dart Maps
You write a map with curly brackets
Maps Explained
{}, and put a colon : between each key and its value
If you use the same key twice, only the last value is kept
Here, every key is a String and every value is an int
This map uses int keys and String values
To create an empty map, write the types in angle brackets before {}, or write the type on the variable
Use length to get the number of pairs
Use toList() if you need them as a list
Dart Access Map Items
You get a value from a map by writing its key inside square brackets
Access Map Items Explained
[]
If the key is not in the map, you get null
A simple fix is to give a default value with the ?? operator
Use containsValue() to check if a value is in the map
If the key already exists, the old value is replaced
The value is given by a small function, written as () => value
update() changes the value of a key, based on its old value
Add ifAbsent to give a value to use when the key is missing
Use clear() to remove all items
Dart Loop Maps
Loop over
Loop Maps Explained
keys to get each key
The ! tells Dart that the value is not null, which is safe here because the key comes from the map itself
Loop over values when you only need the values
Each entry has a key and a value property
You can also use if inside the loop
You give it a function with two parameters, the key and the value, and it runs the function once for each pair
Dart Collection if/for
Note that there are no curly brackets around the item
If the condition is
Collection if/for Explained
false, the item is left out
You can also add an else part, to pick one of two items
Put a for loop inside a literal to add one item for each run of the loop
You can mix normal items and a for in the same literal
A classic counting loop works too
You can put an if inside a for, to keep only some items
Collection if and for also work in set literals
In a map literal, each item is a key: value pair
Dart Spread Operator
It takes all the items from one collection and puts them into a new list, set or map literal
Without the three dots, the whole list would be added as one item
The spread operator is an easy way to join two or more lists into a new list
This also makes the spread operator a simple way to copy a list
The new set still has no duplicates
If the same key appears twice, only the last value is kept
It adds the items if the collection is not
Spread Operator Explained
null, and adds nothing if it is null
You can use the spread operator together with collection if, to add many items when a condition is true
Dart Functions
To call (run) a function, write its name followed by parentheses and a semicolon
A function can be called as many times as you want
All other functions only run when your code calls them
The order does not matter, so you can call a top-level function that is written further down in the file
Instead of
Functions Explained
void, you write the type of the value, and use the return keyword
A small example, with a parameter called name
Dart Parameters
This function has one parameter, called
Parameters Explained
name, of type String
You can have as many parameters as you want, separated by commas
An optional parameter that you do not send is null, so its type must be nullable, like String?
Because the parameter always has a value, its type does not need to be nullable
Here is a function with one required parameter and two optional parameters with default values
Dart Named Parameters
When you call the function, write the name, a colon
Named Parameters Explained
: and the value
If it has no default value, it is null when you leave it out, so its type must be nullable
The default value is used when the argument is left out
A function can have positional parameters first, followed by named parameters
Dart Return Values
This is called returning a value, and you do it with the
Return Values Explained
return keyword
You can store the returned value in a variable, and use it later
The value after return must match this type
This lets you return early when you already know the answer
An early return inside a loop stops both the loop and the function
You can still use return; without a value, to stop the function early
To return several values, you can put them in a list and return the list
Dart Arrow Functions
This is a normal function that squares a number
Here is the same function, written with the arrow syntax
Arrow functions can take more than one parameter
They can return a string
They can also return a
Arrow Functions Explained
bool, which is useful for checks
You can use the conditional operator ? : to choose between two values in one expression
This is common when the function only calls print()
When a function needs more than one statement, use a normal function with curly brackets
Dart Anonymous Functions
This means you can store a function in a variable, and call it with the variable name
Anonymous functions can also use the arrow syntax
The
Anonymous Functions Explained
forEach() method calls the function once for every item in the list
The map() method uses a function to change every item, and gives back the new items
The where() method keeps only the items where the function returns true
The type int Function(int, int) means "a function that takes two int values and returns an int"
You can also pass a named function, without the parentheses
With the typedef keyword, you can give a function type a short name
Dart Closures
In this example, the anonymous function uses the variable
Closures Explained
greeting from main()
The function makeCounter() creates a variable count and returns a function that adds 1 to it
So two counters do not share their values
Here, makeMultiplier() returns a function that multiplies a number by factor
It uses the variable itself, so it always sees the current value
Dart Scope
It can only be used inside that function
To use the value after the block, declare the variable before the block
The loop variable of a
Scope Explained
for loop also belongs to the loop only
It can be used everywhere in the file, in every function
An inner block can use the variables of all the blocks around it
This is called shadowing, because the inner variable hides the outer one
The same happens with an inner block inside a function
Dart Recursion
This function counts down from a number to 1, by calling itself with a smaller number each time
This function adds all numbers from 1 to
Recursion Explained
n
Factorial is a classic example of recursion
The same function can be written in one line with the arrow syntax and the conditional operator
This function adds all the numbers in a list, by taking the first item and calling itself with the rest of...
This loop gives the same result as the recursive sum() function
Dart OOP
This is why values have properties and methods that you can use with a dot
OOP Explained
.
We use it to create two car objects
Dart Classes/Objects
Then use a dot
Classes/Objects Explained
. to read the fields of the object
Each object has its own copy of the fields, so changing one object does not change the others
Methods describe what an object can do, and they can use the fields of the object
In the method below, brand alone means the parameter, and this.brand means the field
The short form Car(this.brand, this.year); puts the arguments directly into the fields
It only prints a general text with the name of the class
You can write your own version of it in your class, with @override on the line above
Dart Constructors
Here is a constructor with a body, which sets the fields and prints a message
When you write
Constructors Explained
this.brand as a parameter, the argument goes directly into the field brand
This also works with final fields, which cannot be changed after the object is created
It comes after a colon :, before the body of the constructor, and the parts are separated by commas
The initializer list can set more than one field, and it can use parameters that are not fields
Use required for the values that must always be given, and a default value for the others
Dart creates each constant object only once, and reuses it when you create the same constant again
Dart Named Constructors
This Point class has a normal constructor, and a named constructor called Point.origin(), which always...
Good names make the code easy to read, because they tell you how the object is created
A named constructor can also use the
Named Constructors Explained
this.x shorthand and have a body
You write a colon, then this(...) with the arguments for the main constructor
A redirecting constructor can also call another named constructor, with this. and the name of that constructor
Dart Factory Constructors
This factory constructor cleans up the name before it calls the normal constructor
In this example, the class keeps all the colors it has created in a Map
Here, the factory
Factory Constructors Explained
Animal.fromSound() decides which kind of animal to create
By convention, this factory is called fromJson
You can use it with map() to turn a list of Maps into a list of objects
Dart Getters and Setters
You create a getter with the
Getters and Setters Explained
get keyword
A short getter is often written with the arrow syntax =>
Other files can read the value, but they cannot change it
You call it with the normal assignment operator =
In this example, the age is only changed if the new value is not negative
Dart Static Members
In this example, the class counts how many cars have been created
Static methods are useful for helper functions that are related to the class
Use it for fixed values that are related to the class
This example uses a static constant and a static field together with normal fields
Static Members Explained
Dart Inheritance
In this example, the
Inheritance Explained
Dog class inherits from the Animal class
Put @override above the method to show that it replaces a method from the superclass
This lets you add to a method instead of replacing it completely
You do this with : super(...) after the parameter list of the subclass constructor
This is called a super parameter
A Dog is an Animal, so you can store it in a variable of type Animal
Dart Abstract Classes
You create an abstract class with the
Abstract Classes Explained
abstract keyword before class
Every subclass must override all abstract methods
Each subclass gives its own version of the abstract method
A list of type List<Shape> can hold circles, squares and any other shape
Dart Interfaces
To use a class as an interface, write
Interfaces Explained
implements and the class name
This is true even when the interface is a normal class with method bodies
Separate the interface names with commas
Write extends first
The code only needs to know the interface, not the real class
Dart Mixins
You add it to a class with the
Mixins Explained
with keyword
Separate the mixin names with commas
A mixin can also have fields
The mixin can then use the members of that class
If you need both, write mixin class
Dart Extension Methods
This extension adds a
Extension Methods Explained
shout() method to all strings
Extension methods can also have parameters
You can extend numbers in the same way
A getter is used without parentheses, just like a field
An extension without a name can only be used in the file where it is written
This is useful when two extensions have a method with the same name
Dart Enums
You create an enum with the
Enums Explained
enum keyword, and separate the values with commas
Every enum value has a name and an index
The values property is a list of all values in the enum, in the order they were written
You can also compare enum values with ==
Enums work very well with the switch statement
This is called an enhanced enum
An enhanced enum can have several fields and getters too
Dart Generics
The type inside the angle brackets
Generics Explained
<> is called a type argument
You can also write the type argument on the value instead of the variable
Inside the class, T stands for the real type that is used later
Separate them with commas, like in Map<K, V>
Write it in angle brackets after the function name
T extends num means that T must be num or a type of number, like int or double
Dart Records
The values can have different types
You get them by their position, with
Records Explained
$1 for the first field, $2 for the second field, and so on
These are called named fields, and you get them by their name
The positional fields are still counted with $1, $2, and the named fields are skipped in that count
Named fields are written inside curly brackets {}
But that one value can be a record, so a function can return several values at the same time
Named fields make the result easier to read
The order of named fields does not matter
Dart Patterns
With a pattern, you can unpack all the fields into variables in one line
This is very useful when a function returns a record
It unpacks the items of a list in order
Other keys in the map are ignored
The wildcard matches any value, but does not create a variable
The code in the
Patterns Explained
if block only runs if the value matches the pattern
This is a safe way to read data where you do not know the types, like a map from a file or a web server
Here, each item in the list is a record
Just like with named fields in records, :x gets the field x into a variable called x
Each entry of a map is a MapEntry object with a key and a value
Dart Switch Expressions
Each case is written as
Switch Expressions Explained
pattern => result, and the cases are separated by commas
Here is the same program written with a switch statement, so you can compare
If you list them all, you do not need _
This is called a logical-or pattern
This is perfect for ranges, like turning a score into a grade
Use && to combine two relational patterns into a range
The case only matches if the pattern matches and the condition is true
Dart Sealed Classes
All the direct subclasses must be written in the same file as the sealed class, so Dart knows every one of...
You do not need a
Sealed Classes Explained
_ case
You can also use object patterns to get the fields directly
Add the missing case, and the program runs again
Sealed classes are often used for results that can be one of a few cases, like a payment that either...
Dart Class Modifiers
Add
Class Modifiers Explained
base to the subclass, and it works
You can still create objects of an interface class
Inside the same file, you can still create subclasses, but just like with base, they must be base, final...
A mixin class can be used both as a normal class and as a mixin
A common one is abstract interface class, which works like a pure interface in other languages
Dart Exceptions
If an exception happens, Dart jumps to the
Exceptions Explained
catch block, and the program continues after it
Use on followed by a type to catch only exceptions of that type
Add catch (e) after the type when you also need the exception object
It is used for cleanup work, like closing a file or a connection
This is useful when a function gets a value it cannot work with
Use rethrow inside a catch block to throw the same exception again
For example, FormatException is an Exception, and RangeError is an Error
Add a second variable to catch to get the stack trace
Dart Custom Exceptions
A custom exception is a normal class that implements the
Custom Exceptions Explained
Exception interface
If your exception class does not have its own toString(), the message is not very helpful
Use on with your class name to catch only your exception, and read its fields
Then you can catch one exact type, or the whole family with the parent type
Custom exceptions are a good way to check input in one place, and handle the problem in another place
Dart Async Intro
Synchronous means that Dart runs one statement at a time, from top to bottom, and each statement must...
Look at the order of the output
This is why the delayed code always runs after the normal code, even with a waiting time of zero
The order in the code does not matter, only the waiting time does
Async Intro Explained
Dart Futures
If you print the future itself, you do not see the value, only the type of the future
The value is passed to the function as a parameter
The value that one
Futures Explained
then() returns is passed to the next one
The catchError() method runs a function when this happens
This is useful when a function must return a future, but the value is already known
The new future completes when all the futures are done, and its value is a list with all the results, in...
Dart async/await
To use
async/await Explained
await in main(), add async after the parentheses and change the return type to Future<void>
If the function returns nothing, the return type is Future<void>
If the future fails, await throws the error, and the catch block runs
A Stopwatch measures how long the code takes
Use await Future.wait() with a list of futures
This works even when the futures have different types, and you can unpack the results with a pattern
Dart Streams
Like
Streams Explained
await, it can only be used inside an async function
A periodic stream never stops by itself, so use take() to keep only the first few events
The optional onDone function runs when the stream is finished
Each method returns a new stream
It comes from the dart:async library, so you must import it at the top of the file
Dart Isolates
This example adds all the numbers from 1 to 100 million in a new isolate
In this example, a timer adds 1 to
Isolates Explained
ticks every 100 milliseconds, while the heavy work runs in another isolate
The calculation runs in the main isolate, so the timer cannot run at all until the calculation is done
The values are copied into the new isolate
The main isolate does not see the change
Dart Imports
After the import, you can use all the names from the library directly
You can import more than one library in the same file
Only the names after
Imports Explained
show are imported
It imports every name from the library, except the names after hide
Then you write the prefix and a dot before each name from the library
Dart Math
The
Math Explained
min() function returns the smaller of two numbers
To find the largest number in a list, you can use reduce() with max
The pow(x, y) function returns x to the power of y
The dart:math library has some well-known numbers as constants
This example uses pi to find the area of a circle
Some math methods are built into the numbers themselves, so they do not need an import
This is useful for testing, and it is why the output below never changes
This example rolls a dice five times, so each number is from 1 to 6
Dart Dates
To create a date, write the year, the month and the day
The
Dates Explained
weekday property is a number from 1 (Monday) to 7 (Sunday)
The example below only prints values that do not change, so you can compare it with your own result
The string should use the format year-month-day, with an optional time after it
Use DateTime.tryParse() if you want null instead of an exception
Use add() and subtract() to move a date forward or back
The difference() method returns the Duration between two dates
Use isBefore(), isAfter() and isAtSameMomentAs() to compare two dates
The padLeft(2, '0') method adds a zero in front of numbers that have only one digit
Dart JSON
The result is a normal string, so you can save it in a file or send it over the internet
To make the JSON easier to read, use a
JSON Explained
JsonEncoder with an indent
A JSON object becomes a Map<String, dynamic>, and you can read the values with their keys
A JSON array becomes a Dart List
Use try and catch when the JSON comes from outside your program
The common way to do this is to give the class two members
Dart RegExp
The
RegExp Explained
hasMatch() method returns true if the pattern is found somewhere in the string
This example checks that a PIN code has exactly 4 digits
To ignore upper and lower case, add caseSensitive: false
The group(0) method of a match returns the text that matched
The allMatches() method finds every match in the string
You can also use map() to get all the matched texts as a list
group(1) is the text of the first group, group(2) is the second, and so on
You can also give a group a name with (?<name>...), and read it with namedGroup()
It replaces every match with a new text
Other string methods that accept a RegExp are split(), contains() and replaceFirst()
Dart User Input
It waits until the user presses Enter, and then returns the line as a
User Input Explained
String
The if-null operator ?? gives a default value when the input is null
Use stdout.write() instead of print() if you want the user to type on the same line as the question
The ?. operator calls trim() only if the input is not null
tryParse() returns null if the text is not a valid number, so the program does not crash when the user...
This program reads lines until there is no more input, and adds up the numbers
Dart Files
The
Files Explained
readAsStringSync() method reads the whole file and returns it as a string
The deleteSync() method deletes the file
The readAsLinesSync() method reads the file and returns a list with one string for each line
Use them with await, so the rest of the program does not have to stop and wait
Use try and catch to handle it