Dart study notes

Grammar

Nine built-in types

Numbers (int, double)
Dart supports two Number types: int (integer value) double (double-precision floating-point number)
Integers support traditional shift operations, shift (<<, >>, and >>>), two's complement (~), bitwise AND (&), bitwise OR (|), and bitwise XOR (^)

assert((3 << 1) == 6); // 0011 << 1 == 0110
assert((3 | 4) == 7); // 0011 | 0100 == 0111
assert((3 & 4) == 0); // 0011 & 0100 == 0000

Strings (String)
Multi-line strings can also be created using three single quotes or three double quotes
In a string, use the expression as ${expression}, if the expression is an identifier (var s = 'string'), you can omit the {}
Strings can be concatenated using the + operator or by juxtaposing multiple strings
Multi-line strings can also be created using three single quotes or three double quotes
Prefix the string with r to create a "raw" string, it will not be escaped

Booleans (bool)

Lists (also known as arrays)

var list = [1, 2, 3];

Prepending the const keyword to a List literal creates a compile-time constant

var constantList = const [1, 2, 3];
// constantList[1] = 1; // This line will cause an error.

spread operator (...) and null-aware spread operator (...?)

var list = [1, 2, 3];
var list2 = [0, ...list];
assert(list2.length == 4);

var list2 = [0, ...?list]; // If the right hand side of the spread operator may be null 
assert(list2.length == 1);

list of Sao operation writing

var nav = ['Home', 'Furniture', 'Plants', if (promoActive) 'Outlet'];
var listOfInts = [1, 2, 3];
var listOfStrings = ['#0', for (var i in listOfInts) '#$i'];
assert(listOfStrings[1] == '#1');

Sets (Set)
set is an unordered collection of a specific set of elements

var names = <String>{}; // Create an empty Set
elements.add('fluorine'); // Add an item to an existing Set
elements.addAll(halogens);
assert(elements.length == 5) // Use .length to get the number of elements in a Set

var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'}; // Infers that the halogens variable is a collection of type Set<String>

// Add the const keyword before the Set variable to create a Set compile-time constant
final constantSet = const {
  'fluorine',
  'chlorine',
  'bromine',
  'iodine',
  'astatine',
};
// constantSet.add('helium'); // This line will cause an error.

Maps (Map)
Map s are objects used to associate keys and values. where both keys and values ​​can be objects of any type. Each key can only appear once but the value can appear multiple times (similar to js, ​​define/add key-value pairs/get values, etc.)
If the retrieved Key does not exist in the Map, it will return a null (undefined in js)

var gifts = {
  // Key:    Value
  'first': 'partridge',
}
// Maps can be created using the Map constructor
var gifts = Map<String, String>();
gifts['first'] = 'partridge';

Adding the const keyword before a Map literal creates a Map compile-time constant (const is the same for many types)
Map can also support the use of spread operators (... and ...?) as well as the if and for operations of collections like List.

Runes (commonly used for character substitution in the Characters API)
For some special characters, emojis, etc. are not commonly used ~ (Unicode characters), you can use the characters defined in the characters package

Symbols (Symbol)
Symbol s can be obtained by prefixing the identifier with #, such as #radix
Symbol literals are compile-time constants

The value null (Null)

basic skills

main()
A special and required top-level function from which Dart applications always start executing.

var
It is used to define variables. Defining variables in this way does not require specifying the variable type. The type (int) of such a variable is determined by its initial value

print()
A convenient way to output and display information

int
Represents an integer number. Some other built-in types in Dart include String, List, and bool

void
A special type that represents a value that will never be used, the return type of a function declared with void and will not return a value

Final and Const
Once defined, it cannot be changed. A final variable can only be assigned a value once; a const variable is a compile-time constant (a const variable is also final)
The difference between them is that const is stricter than final. Final only requires that the value of the variable remains unchanged after initialization, but through final, we cannot know the value of this variable at compile time (before running); and what const modifies is a compile-time constant, and we already know its value at compile time. value, obviously, its value is also immutable.

final bad =  [];   //List<int>
bad.add(1);    //Execute normally, adding members to the variable reference object

assert
Calls to assert() will be ignored in production code. During development, assert(condition) will throw an exception when the condition is false

some concepts
Everything in Dart is an object. All variables refer to objects, and each object is an instance of a class. Numbers, functions, and null are all objects. Except for null (if you have null safety enabled), all classes inherit from the Object class

Null-safe: A variable cannot be null when it is not declared as a nullable type. You can declare a type as nullable by putting a question mark (?) after the type (similar to ts)
If you know for sure that an expression won't be null, but Dart doesn't think so, you can assert that the expression is not null by adding ! after the expression e.g.: int x = nullableButNotNullInt!

Dart is a strongly typed language, but specifying the type when declaring a variable is optional because Dart can do type inference

If you want to explicitly state that any type is allowed, use Object. If the empty type is turned on, then Object?

Dart supports generics like List<int> (representing a list of int objects) or List<Object> (representing a list of objects of any type)

Dart supports top-level variables, as well as defining variables (static and instance variables) that belong to a class or object. Instance variables are sometimes called fields or properties.

Dart supports top-level functions (such as the main method), but also supports defining functions that belong to classes or objects (i.e. static and instance methods). You can also define functions within functions (nested or local functions)

There is a difference between expressions and statements in Dart. Expressions have values ​​and statements do not (it is actually the same as js)

An identifier starting with an underscore (_) indicates that the identifier is private within the library

If an object's reference is not limited to a single type, it can be specified as Object (or dynamic)

var name = 'Bob'; // Create a variable and initialize it
Object name = 'Bob'; // any type of name
String name = 'Bob'; // The specified type is String

Variables of uninitialized and nullable types have a default initial value of null

function

Functions are also objects and are of type Function
Support default parameter value definition, if no default value is specified, the default value is null
Functions can be assigned to a variable or as an argument to other functions
All functions have return values. The last line of a function that does not show a return statement defaults to executing return null
define a function

bool isNoble(int atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}
// or
isNoble(atomicNumber) {
  return _nobleGases[atomicNumber] != null;
}

If the function body contains only one expression, you can use the shorthand syntax (arrow function)

bool isNoble(int atomicNumber) => _nobleGases[atomicNumber] != null;

Syntax => expression is shorthand for { return expression; } , => is also sometimes called an arrow function

parameter

There are two forms of parameters: required parameters and optional parameters. Required parameters are defined before the parameter list, optional parameters are defined after the required parameters

named parameters

Named parameters are optional by default unless they are specifically marked as required
When defining a function, use {parameter1, parameter2, …} to specify named parameters

void enableFlags({bool? bold, bool? hidden}) {...}

When calling a function, you can use parameter_name: parameter_value to specify the value of a named parameter

enableFlags(bold: true, hidden: false); 

Use required to indicate that a named parameter is required and the caller must provide a value for the parameter

String printUserInfo(String username, {int age=10, String sex="male"}) {//line parameter    
  return "Name:$username---gender:$sex--age:$age";
}

String printInfo(String username, {required int age, required String sex}) {//line parameter    
  return "Name:$username---gender:$sex--age:$age";
}
anonymous function

The content in curly brackets is the function body

([[type] parameter[, ...]]) {
  function body;
};
const list = ['apples', 'bananas', 'oranges'];
list.forEach((item) {
  print('${list.indexOf(item)}: $item');
});
lexical scope

The scope of the variable is determined when the code is written, and the variables defined in the curly brackets can only be accessed within the curly brackets

Lexical closure

A closure is a function object that can access variables in its lexical scope even if the function object is called outside its original scope

/// Returns a function that adds [addBy] to the
/// function's argument.
Function makeAdder(int addBy) {
  return (int i) => addBy + i;
}

void main() {
  // Create a function that adds 2.
  var add2 = makeAdder(2);

  // Create a function that adds 4.
  var add4 = makeAdder(4);

  assert(add2(3) == 5);
  assert(add4(3) == 7);
}

operator

Most of them are similar to js, ​​some cases need to be paid attention to

arithmetic operators

Similar to js, ​​but with an additional ~/ division and rounding (5 ~/ 2 == 2)

relational operator

Similar to js, ​​but to determine whether two objects x and y represent the same thing, use ==

type judgment operator

as, is, is! operators are operators that determine the type of an object at runtime
as
type conversion (also used to specify class prefix))

is
Returns true if the object is of the specified type

is!
Returns false if the object is of the specified type

assignment operator

You can use = to assign values, and you can also
= *= %= >>>= ^=
+= /= <<= &= |=
-= ~/= >>=

// Use ??= to assign a value to a variable with a null value
b ??= value;
// Using assignment and compound assignment operators
var a = 2; // Assign using =
a *= 3; // Assign and multiply: a = a * 3
assert(a == 6);
Logical Operators

!expression Negates the result of an expression (ie true becomes false, false becomes true)
|| logical or
&& logical AND

& bitwise AND
| bitwise OR
^ bitwise XOR
~expression bitwise negated (ie "0" becomes "1" and "1" becomes "0")
<< bit shift left

bit shift right

unsigned right shift

conditional expression

two special operators
Condition ? Expression 1 : Expression 2
expression 1 ?? expression 2
Returns the value of expression1 if it is non-null, otherwise executes expression2 and returns its value

cascade operator

Cascading operators (.., ?..) allow you to call variables or methods of multiple objects consecutively on the same object -- not very understandable

flow control statement

Similar to js, ​​so I won't go into details

kind

See: https://dart.cn/guides/langua...

Generics

https://dart.cn/guides/langua...

asynchronous

https://dart.cn/guides/langua...

Tags: Flutter dart

Posted by eashton123 on Mon, 11 Jul 2022 08:32:26 +0530