当前位置:网站首页>Flutter series -dart basic grammar learning

Flutter series -dart basic grammar learning

2022-06-22 19:28:00 Liuyichu

One 、 Variable

Variable is a reference , according to Dart in “ Everything is object ” principle , That is, variables store references to objects , Or they all point to objects .

1.1. Declare variables :

//1. Do not specify type 
var name = 'aaa';
//2. Specify the type 
String name = 'aaa';

Because there is type derivation , So the two implementations have the same effect , It is officially recommended that local variables in functions should be used as much as possible var Statement .

When the variable type is not clear , have access to dynamic keyword

//3. Use dynamic keyword 
dynamic name = 'aaa';

1.2. The default value is

The default value for uninitialized variables is null. Even if the variable is numeric, the default value is null, Because in Dart Everything in is the object , Number types are no exception .

int lineCount;
assert(lineCount == null);

Tips : In the production mode code assert Assertion ) Functions are ignored , Will not be called . In the development process , assert(condition) It will be in Africa true Throw an exception under the condition of .( notes : Dart 1.x There are two operation modes: production mode and inspection mode , Dart 2 Remove the check mode .)

1.3.Final and Const

 use final Decorated variable , It must be initialized at definition time , Its value cannot be changed after initialization ;
const Used to define constants .

The difference is ,const Than final More stringent .final It just requires that the value of the variable remains unchanged after initialization , But through final, We can't compile ( Before you run ) Know the value of this variable ; and const The modification is a compile time constant , We already know its value at compile time , obviously , Its value is also immutable .

How to understand

One final Variable can only be set once , The difference is :const The variable is a Compile time constants ,final Variables are initialized the first time they are used .
Generally speaking, it means , final It will be initialized only when it is used , If only defined , Without being used , Then this variable has not been initialized ( It can be understood as ’ Lazy loading ’); and const Decorated variable , Once defined, it is initialized during compilation .

Const Keywords can not only be used to declare constant variables . It can also be used to create constant values , And declare constructors that create constant values . Any variable can have a constant value .

var foo = const [];
final bar = const [];
const baz = []; // Equivalent to `const []`

Not Final, Not const The variables of can be modified , Even if these variables have ever referenced const value .

foo = [1, 2, 3]; //  I used to quote  const []  Constant values .

Const The value of a variable cannot be changed :

baz = [42]; // Error:  Constant variables cannot be modified by assignment .

Two 、 Built in type

Be careful : stay dart in , All types are objects , There is no basic data type ( Naturally, there is no unpacking ).
For standard Java Eight built-in basic data types of ,Dart There are several built-in types :
Numbers The number
Strings character string
Booleans Boolean value
Lists list ( Array )
Sets aggregate
Maps aggregate
Runes Symbolic characters ( Used to represent... In a string Unicode character )
Symbols identifier

2.1.Numbers

1.num Is the parent of the number type , There are two subclasses int and  double, For integer and floating point respectively .
2.int and  double stay java Are keywords , And in the dart Class in 
3.int Determine the occupancy length according to the compilation platform , The longest is 8 byte 
4.int  There is one bitLength() Method , You can determine the number of bits that the storage needs to occupy 

from Dart 2.1 Start , When necessary int The literal amount is automatically converted to double type .

double z = 1; //  amount to  double z = 1.0.

2.2.Strings

1.Dart The string is UTF-16 Encoded character sequence , You can use single or double quotes to create a string , And single and double quotation marks can be nested , Some of it can be avoided \ The use of escape characters .( stay dart in , Both string and character are String type , No, char type .)

void test() {
    
  String s1 = "\"test\"";
  String s2 = '"test"';
  print(s1);
  print(s2);
   The above output is double quoted "test" character string 
}

2. You can use three single or double quotes to create a multiline string object

var s1 = '''
You can create
multi-line strings like this one.
''';

var s2 = """This is also a
multi-line string.""";

3. have access to r Prefix creation ” original raw” character string ( No escape )

var s = r"In a raw string, even \n isn't special.";//print:In a raw string, even \n isn't special.

4. Interpolation expression : In the string, you can use $+{ Variable } Methods reference variables to splice strings .
Or put multiple strings together to achieve splicing .
notes : If the expression is an identifier , It can be omitted {}, If the result of an expression is an object , be Dart Will call the object toString() Function to get a string

void main() {
    
  String s1 = "Juice";
  String s0 = "is";
  String s2 = "My name ${s0} ${s1}";//My name is Juice  Equivalent to : String s2 = "My name $s0 $s1";
  String s3 = "My name is"" Juice";//My name is Juice  Of course, it can be like java The same goes through  +  Operators concatenate strings 

}

2.3. Booleans

Dart Use bool Types represent Boolean values . Dart It's just literal true and false It's the boolean type , Both objects are Compile time constants .

2.4. Lists

stay Dart in , Array is List object .
Yes List Traversal is also related to Java equally .

void main() {
    
  List<int> list = new List();
  List<int> list1 = List();
  List<int> list2=[1,2,3,4,5];// Tips :Dart infer list The type of List<int> . If you try to add a non integer object to this List in , The parser or runtime will raise an error . For more information , You can learn   Type inference .
  print(list2[1]);// Get the subscript as 1 Value 
  // Traversal array 
  //iter for-in  Templates 
  for (var o in list) {
    

  }
  //itar for-i Templates 
  for (var i = 0; i < list1.length; ++i) {
    
    var o = list1[i];

  }
}

stay List Add... Before the literal amount const keyword , Can define List Compile time constants of type :

var constantList = const [1, 2, 3];
// constantList[1] = 1; //  Uncomment can cause errors .

2.5.Sets

dart Medium set It's a Unordered without repeating elements Set
Dart by Set Provides Set Literal and Set type .
Version hint : although Set type Has always been a Dart The core of , But in Dart2.2 It's only in China that Set Literal .

Set<String> cls = {
    " Xiao Wang ", " Xiao Yang "};// use Set type ( keyword ) The way to create 
var sets= {
    'a', 'b', 'c', 'd', 'e'};// Create... Literally , namely var keyword 

Be careful : Dart infer sets The type is Set . If you try to add a value of the wrong type to it , An error is thrown by the parser or during execution .

To create an empty set , Use... With type parameters in front of it {} , Or will {} Assign a value to Set Variable of type :

var names = <String>{
    };
// Set<String> names = {}; //  It's ok .
// var names = {}; //  This creates Map still Set?

yes Set still Map ?
Map Literal quantity is the same as Set The grammar of literal quantity is very similar . Because first there was Map Alphabetic grammar , therefore {} The default is Map type .
in other words , If you forget {} Comment type or assign to a variable of undeclared type , that Dart Will create a type of Map<dynamic, dynamic> The object of .

stay Set Add before the literal amount const , To create a compile time Set Constant :

final constantSet = const {
    
  'aa',
  'bb',
  'cc',
  'dd',
  'ee',
};
// constantSet.add('ff'); // Uncommenting this causes an error.

2.6.Maps

1. Keys and values can be any type of object .
2. Each key appears only once ,  And a value can appear many times 
3. For the nonexistent key, Then return to null
4. Ergodic and java Agreement 
5.const Yes Map Please refer to the above List
var gifts = {
    
  // Key: Value
  'first': 'partridge',
  'second': 'turtledoves',
  'fifth': 'golden rings'
};

var nobleGases = {
    
  2: 'helium',
  10: 'neon',
  18: 'argon',
};

Tips : Dart Will gifts The type of is inferred as Map<String, String>, nobleGases The type of is inferred as Map<int, String> . If you try on the top map Add error type to , Then the parser or runtime will raise an error .

above Map Objects can also use Map Constructor creation :

var gifts = Map();
gifts['first'] = 'partridge';
gifts['second'] = 'turtledoves';
gifts['fifth'] = 'golden rings';

var nobleGases = Map();// Tips :  Why is there only Map(), Instead of using  new Map(). Because in  Dart2 in ,new Keywords are optional . For more information , Use of reference constructors .
nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';

similar JavaScript , add to key-value To the existing Map in :

var gifts = {'first': 'partridge'};
gifts['fourth'] = 'calling birds'; // Add a key-value pair

similar JavaScript , From a Map Get one of value:

var gifts = {
    'first': 'partridge'};
assert(gifts['first'] == 'partridge');

If Map Does not contain the key, that Map return null:

var gifts = {
    'first': 'partridge'};
assert(gifts['fifth'] == null);

Use .length Function to get the current Map Medium key-value For quantity :

var gifts = {
    'first': 'partridge'};
gifts['fourth'] = 'calling birds';
assert(gifts.length == 2);

establish Map Type runtime constant , To be in Map Put the keyword before the literal quantity const.

final constantMap = const {
    
  2: 'helium',
  10: 'neon',
  18: 'argon',
};

// constantMap[2] = 'Helium'; //  Uncomment can cause errors .

2.7.Runes( Less daily development and use )

stay Dart in , Rune Used to represent... In a string UTF-32 Encoded characters .

Unicode Defines a global writing system code , All the letters used in the system , Numbers and symbols correspond to unique numeric codes . because Dart A string is a series of UTF-16 Coding unit , So it's going to be represented in a string 32 position Unicode Values require special syntax support .

Express Unicode The common way to code is , \uXXXX, here XXXX It's a 4 Bit 16 Hexadecimal number . for example , Cardioid symbol () yes \u2665. For special non 4 Number , Put the code value in the brace . for example ,emoji My smile (�) yes \u{1f600}.

void main() {
    
  var clapping = '\u{1f44f}';
  //5 individual 16 Base number   Need to use {}
  print(clapping); //
  // get  16 Bit code unit 
  print(clapping.codeUnits); //[55357, 56399]
// get unicode Code 
  print(clapping.runes.toList()); //[128079]
  Runes input = new Runes(
      ' \u{1f47b} \u{1f44d}');
  print(String.fromCharCodes(input));// Output   
}

2.8.Symbol( Less daily development and use )

One Symbol Objects represent Dart An operator or identifier declared in a program . You may never need to use Symbol , But refer to the identifier by name API when , Symbol It's very useful . Because code compression will change the name of the identifier , But it doesn't change the symbol of the identifier . By literally measuring Symbol , That is to say, add a # Number , To get the identifier Symbol .

#radix
#bar

Symbol Literal quantities are compile time constants .

3、 ... and 、 Optional parameters

Dart Method has two types of parameters : Necessary and optional . We generally know what is necessary , Here is the main analysis Optional parameters .

If both optional and required parameters are included , The required parameters are in front of the parameter list , Optional number follows .

Optional parameters can have a default value , The default value is used when the caller does not specify a value . This and kotlin The syntax is similar . Secondly, the optional parameters can be divided into :

Optional named parameters( Optional named parameters )

Optional positional parameters( Optional position parameters )

3.1. Optional named parameters

The defining function is , Use {param1, param2, …} To specify optional named parameters :

  void test(int num, {
    String name, int range}) {
     // among num It's a required parameter  name and range Is an optional named parameter 
  }

Optional parameters can have default values , Such as :

 void test(int num, {
    String name, int range = 10}) {
    

  }

When calling a method that contains optional named parameters , Need to use paramName:value Specifies which optional parameter to assign a value to , such as :

   test(10,range: 1);

3.2. Optional position parameters

In method parameters , Use "[]" The enclosing parameters are optional positional parameters , You can also have default values , such as :

  void test(int num, [String where, int range]) {
    

  }
  
  void test1(int num, [String where = 'Shanghai', int range]) {
    

  }

When calling a method that contains optional positional parameters , No need to use paramName:value In the form of , Because the optional location parameter is location , If you want to specify a parameter value at a certain position , Must have a value in the previous position , Even if the previous value has a default value . such as :

  	test(10,10); // Unworkable 
    
    test(10,'shenzhen',10); // feasible 
    
    test1(10,10); // Unworkable 
    
    test1(10,'shenzhen',10); // feasible 
    

Four 、 Control statement flow

You can control it in any of the following ways Dart Program flow :
if … else
for loop
while and do-while loop
break and continue
switch … case
assert

Basically follow java equally

5、 ... and 、 abnormal

Dart2 The abnormity and Java It's very similar .Dart2 The exception is Exception perhaps Error( Including their subclasses ) The type of , It can even be right or wrong Exception perhaps Error class , You can also throw , But this is not recommended .

Exception Mainly exceptions that the program itself can handle , such as :IOException. This is also the main exception we handle .

Error It's a bug that the program can't handle , Indicates a more serious problem in running an application . Most of the errors have nothing to do with what the coder does , It means code runtime DartVM What happened . such as : out of memory (OutOfMemoryError) wait .

And Java The difference is ,Dart2 It does not detect whether an exception is declared , In other words, the method or function does not need to declare which exceptions to throw .

5.1. Throw an exception :

Dart The program can throw any non null object , Not limited Exception and Error object . But this is not recommended . in addition ,throw Statements in Dart2 Is also an expression , So it could be =>.

testException(){
    
  throw "this is exception";
}
testException2(){
    
  throw Exception("this is exception");
}

It can also be used. =>

void testException3() => throw Exception("test exception");

5.2. Capture exception :

on You can catch exceptions of a certain class , But we can't get the exception object ;
catch Exception objects can be caught . These two keywords can be combined .
rethrow You can re throw the caught exception .
finally Internal statements , No matter whether there is any abnormality , It will be carried out .
Follow java Very similar .

6、 ... and 、 Other

This part is just a brief introduction

Dart It's a class based and mixin Object oriented language of inheritance mechanism . Each object is an instance of a class , All classes inherit from Object. . be based on * Mixin Inherit * Means that each class ( except Object Outside ) There is only one superclass , The code in one class can be reused in multiple other inherited classes .

Version hint : stay Dart 2 in new Keywords become optional .
That is, when creating objects new It can be omitted .

Use ?. Instead of . , It can be avoided because the object on the left may be null , The resulting anomaly :
This heel kotlin It's very similar inside

//  If  p  by  non-null, Set its variables  y  The value of is  4.
p?.y = 1;

Others such as generics , library , Asynchronous Support , Metadata , Notes and so on .

原网站

版权声明
本文为[Liuyichu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221754259709.html