variable
Declaration of variables
- var
- dynamic
- Object
-
Declare an uninitialized variable whose type can be changed
/ / variable /// Three slash document comments /// The return type void can be omitted, and the return value is null void main(){ ///----------------------- variable declaration ----------------- // declare an uninitialized variable whose type can be changed var data; data = "HelloWorld"; dynamic data1; data1 = "HelloWorld1"; data1 = 123; Object data2; data2 = 'HelloWorld2'; data2 = 123; print([data,data1,data2]); } /// Print effect lib/1-variables.dart:1: Warning: Interpreting this as package URI, 'package:flutter_test3/1-variables.dart'. [HelloWorld, 123.123] Copy the code
-
Declare an initialized variable whose type cannot be changed
var variablel = 'HelloWorld'; // A variable is a reference. A variable named variableL refers to a String with the content 'HelloWorld'. // variablel = 123; // After initialization, the type of the variableL variable is inferred to be String, and its type cannot be changed Copy the code
-
The types of variables declared by dynamic and Object can still be changed after initialization
dynamic variable2 = "HelloWorld"; variable2 = 123; // variable2.test(); // Call the test() method that does not exist, compile and pass, run an exception. Type is not checked during compilation Object variable3 = 'HelloWorld'; variable3 = 123; // variable3.test(); // Call to nonexistent test() method, failed compilation. Types are checked at compile time Copy the code
-
Declare a variable with a deterministic type. The type of the variable cannot be changed
String name3 = "HelloWorld"; // name3 =123; // The type of the variable cannot be changed Copy the code
Summary of variable Declarations
-
Var: can be any type if there is no initial value
-
Dynamic: Any dynamic type. The type is not checked during compilation
-
Object dynamic arbitrary type. The type is checked at compile time
The difference between:
- The only difference is that if var has an initial value, the type is locked
The default value
-
Variables that are not initialized default to NULL
Everything is an object, and the default value for an object is NULL
bool isEmpty; print((isEmpty == null)); Copy the code
Final and const
-
For variables that are final or const, the variable type may be omitted
final FVariablel = "HelloWorld"; // final String FVariablel = "HelloWorld"; const cVariablel = "HelloWorld"; // const String cVariablel = "HelloWorld"; Copy the code
-
Variables that are final or const cannot be modified.
// fVariable1 = '123'; // cVariable1 = '123456'; Copy the code
-
If it is a class-level constant, use static, const.
DateTime; DateTime static const int Monday = 1; Copy the code
-
A const may be initialized with the value of another const.
const width = 100; const height = 100; const square = width * height; Copy the code
-
Const assignment declarations may be omitted
const List clist = [1.2.3]; // const List clist = const [1, 2, 3]; // Before dart 2, const assignments must be declared const print("\n\n\n"); print(clist); Copy the code
-
You can change the value of a non-final, nonconst variable even if it once had a const value
var varList = const [1.2.3]; final finalList = const [1.2.3]; const constList = [1.2.3]; print([varList, finalList, constList]); varList = [1]; // constList[1]; // finalList[1]; print("\n\n"); print([varList, finalList, constList]); Print effect --/* * ** [[1, 2, 3], [1, 2, 3], [1, 2, 3]] * [[1], [1, 2, 3], [1, 2, 3]] * / Copy the code
-
The immutability caused by const is transitive
final List ls = [1.2.3]; ls[2] = 444; print(ls); const List cLs = [4.5.6]; // cLs[1] = 4; print("\n"); print(ls); Error:/* * * * Unhandled exception: Unsupported operation: Cannot modify an unmodifiable list #0 UnmodifiableListBase.[]= (dart:_internal/list.dart:90:5) #1 main (package:flutter_test3/1-variables.dart:103:6)* / Copy the code
-
The same const constant is not created repeatedly in memory
final finalList1 = [1.2.3]; final finalList2 = [4.5.6]; print("\n"); print(identical(finalList1, finalList2)); // IDENTICAL checks to see if two references point to the same object const constList1 = [1.2]; const constList2 = [1.2]; print("\n"); print(identical(constList1, constList2)); // IDENTICAL checks to see if two references point to the same object Copy the code
-
Const needs to be a compile-time constant
final DateTime finalDateTime = DateTime.now(); // const DateTime constDateTime = DateTime.now(); // Datetime.now () is the calculated value at runtime const sum = 1 + 2; // The value obtained by a basic operation using a literal of the built-in data type const aConstNum = 0; const aConstBool = true; const aConstString = 'a constant string'; const aConstNull = null; const validConstString = '$aConstNum, $aConstBool, $aConstString, $aConstNull'; print(validConstString); // Interpolation using compile-time constants that evaluate to null or a number, string, or Boolean Copy the code
Final and const summaries
In common
- The declared type can be omitted
- No value can be assigned after initialization
- Cannot be used with var
Differences (Points to note)
- Class level constants, using static, const.
- Const may be initialized with the value of another const
- Const may be initialized with the value of another const
- You can change the value of a nonfinal, nonconst variable, even if it once had a const value
- The immutability caused by const is transitive
- The same const constant is not created repeatedly in memory
- Const needs to be a compile-time constant
Built-in types
Number value (num, int, double)
int i = 1; / / integer
double d = 1.0 ;// Double b4-bit floating-point number
int bitLength = i.bitLength;
print('bitLength:${bitLength}'); //bitLength specifies the number of bits needed for int.
double maxFinite = double.maxFinite;
print('maxFinite: ${maxFinite}'); //maxFinitedouble Specifies the maximum value
Int and double are subclasses of num
num n1 = 1;
num n2 = 1.0;
// The decimal and hexadecimal values are supported
int il = oxfff;
// Scientific enumeration
double dl = 1.2 e2; / / 120.0
/ / conversion
//String > int
int i2 = int.pasrse('1');
double d2 = 1;// When double is int, int is automatically converted to double
print(D2: '${d2}');
int i2 = int.try.parse('1.0');/ / returns null
//int > String
int is = 123;
String s = 123.toString;
Copy the code
String String
Dart strings are utF-16 encoded sequences of characters that can be created using single or double quotes
var name = 'HelloWorld';
// You can use an expression in a string: ${expression}. If the expression is an identifier, you can omit {}. If the result of the expression is an object, Dart calls the object's toString() function to get a string
var names = 'HelloWorld ${name}';
// The r prefix creates a "raw" string
var rawNames = r"HelloWorld ${name}";
print('name:${names}');
print('rawNames :${rawNames}');
// If the result of the expression is an object, Dart calls the object's toString() function to get a string.
pint(Map);
// You can create a multi-line string object with three single or double quotes
var multiLinesString = '''
Java Android
Flutter''';
pint('mutiLinesString:${mutiLinesString}');
/// StringBuffer
var sb = StringBuffer(a);// Dart 2 can omit newsb.. write('aaa').. write('bbb').. write('ccc');/ /.. Cascading implements chained calls
sb.writeAll([aaa,bbb,ccc],', ');// The second argument represents the delimiter, which is used to concatenate the data in the first argument list
pint('sb:${sb}');
Copy the code
Booleans Boolean value (bool)
/ / bool: true and false
bool isNull;
print('isNull: ${isNull}');
Copy the code
List (array List)
// Declare an automatic length array
List growableList = new List(a);//List growbleList = new List().. length = 3;growbleList.. add(1).. add(2).. add('HelloWorld');
pint('growbleList: ${growbleList}');
// Declare an array of fixed length
var list = List(6);// This can be declared with var or List
list[0] = "Java";
list[1] = "Android";
list[2] = "Dart";
list[3] = "Flutter";
list[4] = "C++";
list[5] = "C"
pint('list:${list}');
// Element fixed type
var typeList = List<String>; typeList.. add("1").. add("2").. add("3");
pint('typeList:${typeList}');
// Common attributes - gets the first element
String first = typeList.fisrt;
pint('typeList.fisrt:$typeFirst');
// The last element
String last = typeList.last;
pint('typeList.last:${last}');
// Number of elements
int typeListLength = typeList.length;
pint('typeListLength:${typeListLength}');
// Whether the element is empty
bool isEmpty = typeList.isEmpty;
pint('typeList.isEmpty:${isEmpty}');
// Whether the element is not empty
bool isNotEmpty = typeList.isNotEmpty;
pint('typeList.isNotEmpty:${isNotEmpty}');
// The array is reversed
可迭代 reversed = typeList.reversed;
print('typeList.reversed:${reversed}');
// The common methods to add, delete, modify, sort, shuffle, copy the child list
var list4 = [];
/ / to add
list4.add(1);
pint('add 1:${list4}');
list4.addAll([2.3.4]);
print('the addAll [4] 2:${list4}');
list4.insert(0.0);
print('the insert (0, 0) :${list4}');
list4.insertAll(1[5.6.7.8]);
print('insertAll (1,,6,7,8 [5]) :${list4}');
/ / delete
list4.remove(5);
print('remove 5 :${list4}');
list4.removeAt(2);
print('remove at 0:${list4}');
/ / change
list4[4] = 5;
print('updata list4[4] to 5 :${list4}');
//range
list4.fillRange(0.3.9);
print('fillRange updata list4[0] - list[2] to 9 :$list4');
可迭代 getRange = list4.getRange(0.3);
print('getRange list4[0]-list[2]:${getRange}');
/ / check
var contains = list.contains(5);
print('contains 5 :${contains}');
var indexOf = list4.indexOf(1);
print('list4 indexOf 1 :${indexOf}');
int indexWhere = list4.indexWhere((test) => test == 5);
print('list4 indexWhere 5 :${indexWhere}');
/ / sorting
list4.sort();
print('list4 sort:${list4}');
/ / shuffle
list4.shuffle();
print('list4 shuffle:${list4}');
// Copy the sublist
var list5 = list4.shulist(1);
print('sublist(1) list5: ${list5}');
/ / operators
var list6 =[8.9];
print('list6:${list6}');
var list7 = list5 + list7;
print('list5 + list6:${list7}');
Copy the code
Set of key value pairs (Map)
// Declare a dynamically typed Map
var dynamicMap = Map(a); dynamicMap['name'] = 'HelloWorld';
dynamicMap[1] = 'android';
print('dynamicMap :${dymaicMap}');
/ / type
var map = Map<int.String> (); map[1] = 'java';
map[2] = 'Android';
print('map :${map}');
// This can also be declared
var map1 = {'name':'Java'.1:'android'};
map1.addAll({'name'.'Flutter'});
print('map1:${map1}');
// Common attributes
// print(map.isEmpty); // Whether to be empty
// print(map.isNotEmpty); // Whether the value is not null
// print(map.length); // Number of key-value pairs
// print(map.keys); / / key collection
// print(map.values); / / the value set
Copy the code
The Set Set (Set)
// Set No duplicate list
var dynamicSet = Set(a); dynamicSet.add('java');
dynamicSet.add('Android');
dynamicSet.add('Flutter');
dynamicSet.add('C/C++');
dynamicSet.add('1');
dynamicSet.add('1');
print('dynamicSet :${dynamicSet}');
// Common attributes are similar to List
// The common method of adding, deleting, modifying and checking is similar to the List
var set1 = {'java'.'Android'};
print('set1: ${set1}');
var differencel2 = set1.difference(set2);
var difference21 = set1.difference(set1);
print('set1 difference set2 :${differencel2}');// Return the set of elements in set1 but not in set2
print('set2 difference set1 :${difference2l}');// Return the set of elements in set2 but not in set1
var intersection = set1.intersection(set2);
print('set1 set2 intersection:${intersection}');Return the intersection of set1 and set2
var union = set1.union(set2);
print('set2 set1 union:${union}');
set2.retainAll(['java'.'Android']);// Retain only (the element to be retained must exist in the original set)
print('set2 only keeps Java Android:${set2}');
Copy the code
Runes Symbol character
/ / with Runes for Unicode characters in the string / / https://copychar.cc/emoji/
String runesStr = '👄';
print(runesStr);
print(runesStr.length); // Indicates two 16-bit characters
print(runesStr.runes.length); // Indicates one 32-bit character
Runes runes = new Runes('\u{1f605} \u6211');
var str1 = String.fromCharCodes(runes); // Use String. FromCharCodes to display character graphs
print(str1);
String str2 = '\u{1f605} \u6211'; // If there are not four values, put the encoding values in curly braces
print(str2)
Copy the code
Symbols identifier
// Mirrors have been removed
Copy the code
function
define
-
Can be defined within a function
void main(){ int add(int x,int y){ return x + y; } print(add(1.2)); } Copy the code
-
You can omit types when defining functions
void main(){ add( x, y){ // Omit is not recommended return x + y; } print(add(3.4)); } Copy the code
-
Support abbreviated syntax =>
void main(){ int add2(int x,int y) => x + y; / / / equivalent int add3(intX,int y){ return x + y; } print(add2(3.4)); print(add3(3.4)); } Copy the code
Optional parameters
-
Optionally named parameters, use {param1,param2,… } to specify named parameters
void main(){ int add3({int x,int y,int z}){ x ?? = 1; x ?? = 2; x ?? = 3; return x + y + z; } print(add3()); } Copy the code
-
For optional positional parameters, put optional parameters in [], and put required parameters before optional parameters
void main(){ int add(int x,[int y ,int z]){ y ?? = 2; z ?? = 3; return x + y + z; } print(add(1)); } Copy the code
-
Optional named parameter defaults (the default must be a compile-time constant). Currently, you can use the equal sign ‘=’ or ‘:’. Before the Dart SDK 1.21, you can only use colons, colon support will be removed later, so you are advised to use the equal sign
void main(){ int add5(int x,[int y =2.int z = 3]) {return x + y +z; } // The preceding required parameter has no name print(add(5,y:10,z:20)); } // The default value of the optional positional parameter (the default value must be a compile-time constant) can only be used with the equal sign "=" void mian (){ int add6(int x,[int y = 2.int z = 3]) {return x + y + z; } print(add6(1)); } // Use list or map as the default, but must be const void func({List list = const [1.2.3].Map map = const {1:1.'fun' :'the whole stack{}})//TODO ---- } Copy the code
Anonymous functions
-
Can be assigned to a variable, called through the variable
// Anonymous function with no parameters var anonFunc1 = () => print('Anonymous function with no arguments'); anonFunction(); // Anonymous functions with parameters var anonFunc = (name) => 'I am ${name}'; print(anonFunc('DevYK')); // Call through (), not recommended(() = >print('Not recommended'()));Copy the code
-
Can be called directly within or passed to other functions
void main(){ List test(List list,String func(str)){ for(var i =0; i < list.length; i++){ list[i] = func(list[i]); }return list; } var list = ['a'.'b'.'c'.'d'.'e']; print(test(list,(str) => str * 2)); // String * int,Dart and Py // The anonymous function used by list.foreach () List list1 = [11.12.13]; list1.forEach((item) => print('$item')); } Copy the code
closure
-
Return Function object (closure)
void main(){ Function makeAddFunc(int x){ x++; return (int y) => x + y; } var addFunc = makeAddFunc(2); print(addFunc(3)); } Copy the code
Function is an alias
-
It can point to any function with the same signature
void main(){ MyFunc myFunc; myFunc = subtsract; myFunc(4.2); myFunc = divide; myFunc(4.2); // The typeDef is passed as an argument calculator(4.2,subtsract); } // Function alias typedef MyFunc(int a,int b); // Define two functions based on the same function signature of MyFunc subtsract(int a,int b){ print('subtsract: ${a-b}'); } divide(int a,int b){ print('divide: ${a / b}'); } // Typedefs can also be passed as arguments to functions calculator(int a,int b,MyFunc func){ func(a,b); } Copy the code
The operator
The suffix operation
-
Conditional member access is similar to., but the left operation object cannot be null, such as foo? Bar Returns null if foo is null, otherwise returns the bar member.
String a; print(a? .length);Copy the code
Take the quotient operator
-
Dividend ÷ divisor = quotient… The remainder, A ~/ B is equal to C, and this C is the quotient. That’s the Java equivalent of /
print(2 / 3); print(2~ /3); Copy the code
Type determination operator
-
As, is, is! Determine the object type at run time
void main(){ // As type conversion num iNum = 1; num dNum = 1.0; int i = iNum as int; double d = dNum as double; print([i,d]); // is Returns true if the object is of the specified type print(iNum is int); Child child; Child childl = new Child(); print(child is Parent);//child is Null print(childl is Parent); // is! Returns False if the object is of the specified type print(iNum is! int); } class Parent {} class Child extends Parent {} Copy the code
Conditional expression
-
The ternary operator condition? expr1 : expr2
bool isFinish = true; StringTextVal = isFinish?'yes':'no'; // expr1 ?? Expr2, if expr1 is non-null, return its value; Otherwise execute expr2 and return its result. bool isPaused; isPaused = isPaused ?? false; / / orisPaused ?? =false; Copy the code
The cascading operator
-
. You can call multiple functions and access member variables on the same object in succession. Strictly speaking, a cascade of two dots is not an operator. Just a Dart special syntax.
StringBuffer sb = new StringBuffer(a); sb .. write('Java') ..write('Android') ..write('\n') ..writeln('DevYK'); Copy the code
Flow control statement
if else
for , forEach , for-in
-
forEach
collection.forEach(item) => print('forEach: ${item}'); Copy the code
-
for-in
for (var item in collection) { print('for-in: $item'); } Copy the code