Dart syntax

1. Dart introduction and environment

1.1 Introduction to Dart:

  • Dart is a computer programming language developed by Google, which can be used in the development of web, server, mobile application and Internet of Things.
  • Dart was born in 2011, claiming to replace JavaScript. But the past few years have been tepid. Until the emergence of Flutter is now being re-emphasized. To learn Flutter, we must first know Dart.
  • Official website: https://dart.dev/

1.2 Dart environment construction:

  • To develop Dart programs locally, we first need to install Dart Sdk
  • Official documentation: Get the Dart SDK | Dart
    • windows (recommended): Dart for Windows
    • mac: If the mac computer does not have the brew tool installed, the first step is to install it: https://brew.sh/
brew tap dart-lang/dart        
brew install dart

1.3 Dart development tools:

  • There are many development tools for Dart: IntelliJ IDEA, WebStorm, Atom, Vscode, etc.
  • Here we mainly explain to you how to configure Dart in VSCode.

1. Find the vscode plugin to install dart

2. Find the vscode plug-in and install code runner; Code Runner can run our files

1.4 Hello Dart

  • Use VSCode, create a new folder and Dart file, and run the output (shortcut key: Control+Option+N)
main() {
  print("Hello World");
}

Two, Dart constants, variables, naming rules

2.1 Dart variables:

  • Dart is a powerful scripting language that does not predefine the variable type, and automatically deduces the type
  • Variables defined in dart can use the var keyword to declare variables by type

like:

    var str    = 'this is var';
    String str = 'this is var';
    int str    = 123;
  • Note: Do not write the type after var, write the type without var, write both var a int = 5; report an error

2.2 Dart constants: final and const modifiers

  • The const value does not change and must be assigned at the beginning
  • final can start without assignment and can only be assigned once; and final not only has the characteristics of const compile-time constants, but the most important thing is that it is a runtime constant, and final is lazy initialization, that is, it is initialized before the first use at runtime
  • The amount that never changes, please use final or const to modify it instead of using var or other variable types.
final name = 'Bob'; // Without a type annotation
final String nickname = 'Bobby';
const bar = 1000000; // Unit of pressure (dynes/cm2)
const double atm = 1.01325 * bar; // Standard atmosphere

2.3 Dart naming rules:

1. Variable names must be composed of numbers, letters, underscores and dollar signs ($).

2. Note: the beginning of the identifier cannot be a number

3. Identifiers cannot be reserved words and keywords.

4. Variable names are case-sensitive eg: age and Age are different variables. In actual use, it is also recommended not to use a word case to distinguish two variables.

5. The identifier (variable name) must see the meaning of the name: it is recommended to use nouns for variable names, and verbs for method names

3. Dart data types

3.1 The following data types are supported in Dart:

  • Common data types:
    • Numbers: int, double
    • Strings: String
    • Booleans (Boolean): bool
    • List (array): In Dart, arrays are list objects, so most people just call them lists
//1、第一种定义List的方式
  var l1=["张三",20,true];
  print(l1);  //[张三, 20, true]
  print(l1.length);  //3
  print(l1[0]); //张三
  print(l1[1]); //20
  //2、第二种定义List的方式 指定类型
  var l2=<String>["张三","李四"];
  print(l2);
  var l3 = <int>[12, 30];
  print(l3);
  //3、第三种定义List的方式  增加数据 ,通过[]创建的集合它的容量可以变化
  var l4 = [];
  print(l4);
  print(l4.length);
  l4.add("张三");
  l4.add("李四");
  l4.add(20);
  print(l4);
  print(l4.length);
  var l5 = ["张三", 20, true];
  l5.add("李四");
  l5.add("zhaosi");
  print(l5);
 // 4、第四种定义List的方式
    //  var l6=new List();  //在新版本的dart里面没法使用这个方法了
    var l6=List.filled(2, "");  //创建一个固定长度的集合
    print(l6);
    print(l6[0]);
    l6[0]="张三";   //修改集合的内容
    l6[1]="李四";
    print(l6);  //[张三, 李四]
    l6.add("王五");  //错误写法  通过List.filled创建的集合长度是固定  没法增加数据
    //通过List.filled创建的集合长度是固定
    var l7 =List.filled(2, "");
    print(l7.length);
    l7.length=0;  //修改集合的长度   报错
    var l8=<String>["张三","李四"];
    print(l8.length);  //2
    l8.length=0;  //可以改变的
    print(l8);  //[]
    var l9=List<String>.filled(2, "");
    l9[0]="string";
    // l8[0]=222;
    print(l9);
      • 1. Literal definition List
      • 2. Specify the type definition List
      • 3. The capacity of the collection created by [] can be changed, and the data can be increased
      • 4. Create a fixed-length collection List.filled(2, "")
    • Maps (dictionary): Generally speaking, a Map is an object related to key-value pairs. Keys and values ​​can be any type of object. Each key appears only once, while a value can appear multiple times
void main(){
  //第一种定义 Maps的方式
    var person={
      "name":"张三",
      "age":20,
      "work":["程序员","送外卖"]
    };
    print(person);
    print(person["name"]);
    print(person["age"]);
    print(person["work"]);
   //第二种定义 Maps的方式
    var p=new Map();
    p["name"]="李四";
    p["age"]=22;
    p["work"]=["程序员","送外卖"];
    print(p);
    print(p["age"]);
}
      • 1. Literal definition of Maps
      • 2. Create an empty Map(), and add data in the form of Key Value
  • Data types that are not used in the project (unused):
    • Runes
      • Runes are UTF-32 encoded strings. It can convert text into symbolic expressions or represent specific text.
 main() {
          var clapping = '\u{1f44f}';
          print(clapping);
          print(clapping.codeUnits);
          print(clapping.runes.toList());
        
          Runes input = new Runes(
              '\u2665  \u{1f605}  \u{1f60e}  \u{1f47b}  \u{1f596}  \u{1f44d}');
          print(new String.fromCharCodes(input));
        }
    • Symbols
      • Symbol objects represent operators or identifiers declared in Dart programs. You'll probably never need to use symbols, but they're useful for APIs that refer to identifiers by name, since minification changes the identifier name but not the identifier symbol. To get the symbol for an identifier, use a symbol literal, which is just # followed by the identifier:
  • In Dart, symbols start with #. You don't need to understand this at the introductory stage, and you may never use it.

3.2 Dart type judgment

Use the is keyword in Dart to judge the type

void main(){
  var str='1234';
  if(str is String){
    print('是string类型');
  }else if(str is int){
     print('int');
  }else{
     print('其他类型');
  }
}

4. Dart operator, conditional judgment, type conversion

4.1 Dart operators:

  • arithmetic operator
    • + - * / ~/ (round) % (round)
  • relational operator
    • ==    !=   >    <    >=   
  • Logical Operators
    • !  &&   ||
  • assignment operator
    • Basic assignment operator = ??=
int b = 6;
b??=23;  表示如果b为空的话把 23赋值给b
    • Compound assignment operators += -= *= /= %= ~/=
  // ~/= 取整等于
  var num = 16;
  num ~/= 5;
  print(num);
  • conditional expression 
    • if  else;  switch case 
  • Ternary operator
    • ?? operator:

4.2 Type Conversion

  • 1. Conversion between Number and String types    
    • Convert Number type to String type toString()
    • Convert String type to Number type int.parse()
      String str='123';
      var myNum1=int.parse(str);
      print(myNum1); //123
      print(myNum1 is int);//true
      String str2='123.1';
      var myNum2=double.parse(str2);
      print(myNum2); //123.1
      print(myNum2 is double); // true
    • You can use try ... catch to prevent problems
    // try  ... catch
     String price='';
      try{
        var myNum=double.parse(price);
        print(myNum);
      }catch(err){
           print(0);
      } 
  • 2. Convert other types to Booleans type
    • isEmpty: Determine whether the string is empty
    • == 0: Determine whether it is 0
    • == null: null
    • isNaN: Determine non-numeric values

Five, Dart loop statement, for loop, do-while loop, break and continue

5.1 ++、--

  • In the assignment operation, if ++ -- is written in the front; at this time, the operation is performed first and then assigned, if ++ -- is written in the back: the operation is performed after the assignment
    var a1=10;
    var b1=a1++;
    print(a1);  //11
    print(b1);  //10
    var a2=10;
    var b2=++a2;
    print(a2);  //11
    print(b2);  //11

5.2 for loop

  • Define a two-dimensional array to print the contents inside
List list=[
          {
              "cate":'国内',
              "news":[
                {"title":"国内新闻1"},
                {"title":"国内新闻2"},
                {"title":"国内新闻3"}
              ]
          },
          {
              "cate":'国际',
              "news":[
                {"title":"国际新闻1"},
                {"title":"国际新闻2"},
                {"title":"国际新闻3"}
              ]
          }
        ];
  • for loop use
        for(var i=0;i<list.length;i++){
            print(list[i]["cate"]);
            print('-------------');
            for(var j=0;j<list[i]["news"].length;j++){
                print(list[i]["news"][j]["title"]);
            }
        }

5.3 while loop / do-while loop

    while(表达式/循环条件){      
    }     
        
    do{
      语句/循环体
    }while(表达式/循环条件);

Note: 1. Don’t forget the final semicolon

2. The variables used in the loop condition need to be initialized

3. In the loop body, there should be conditions to end the loop, otherwise it will cause an infinite loop.

    var j=10;   
    do{
      print('执行代码');
    }while(j<2);

5.4 break和continue

  • break statement function:

1. Make the process jump out of the switch structure in the switch statement.

2. Make the process jump out of the current loop in the loop statement, and the loop will terminate when encountering a break, and the following code will not be executed

    • emphasize:

1. If the break statement has been executed in the loop, the statement after the break in the loop body will not be executed.

2. In a multi-layer loop, a break statement can only jump out one level

    • break can be used in switch case as well as in for loop and while loop
  var sex="男";
  switch (sex) {
    case "男":
      print('男');
      break;
    case "女":
      print('男');
      break;
    default:
  }
  • The function of the continue statement:
    • [Note] It can only be used in a loop statement to end this loop, that is, skip the unexecuted statement under the loop weight, and then judge whether to execute the loop next time.
    • continue can be used in for loops and while loops, but it is not recommended to be used in while loops, because it is easy to loop endlessly if you are not careful
    for(var i=1;i<=10;i++){
      if(i==4){
        continue;  /*跳过当前循环体 然后循环还会继续执行*/
      }
      print(i);
    }
  • 六、Dart中List、Set、Map、forEach/map/where/any/every

6.1 Commonly used properties and methods in List:

  • Common properties:

length length

reversed

isEmpty is empty

isNotEmpty is not empty

  • Common methods:

add increase

addAll stitching array

indexOf finds the incoming specific value

remove deletes the incoming specific value

removeAt removes the incoming index value

fillRange(start,end,[fillValue]) Modify, from the start index to the end index, fill the value in [fillValue], not including the end index.

insert(index,value); Insert at specified position

insertAll(index,list) Insert the List at the specified position

toList() Convert other types to List

join(String) List is spliced ​​into a string through the String in parentheses

split(String) String is split into List by (String)

Shorthand for forEach loop traversal

map modifies the original data according to the conditions and returns

where to filter based on the given qualification

any returns true as long as there is something in the collection that satisfies the condition

Every each satisfies the condition and returns true, otherwise returns false

//fillRange的使用
    List myList=['香蕉','苹果','西瓜'];
    myList.fillRange(1, 2,'aaa');  //修改
    print(myList);//[香蕉, aaa, 西瓜]
    myList.fillRange(1, 3,'aaa');  
    print(myList);//[香蕉, aaa, aaa]
    //insert的使用
    myList.insert(1,'aaa');      //插入  一个
    print(myList);//[香蕉, aaa, aaa, aaa]
    myList.insertAll(1, ['aaa','bbb']);  //插入 多个
    print(myList);//[香蕉, aaa, bbb, aaa, aaa, aaa]
  • According to the similarity of many grammars, it is relatively easy to understand forEach, map, where, any, and every here, but they just change their names.
//1. forEach遍历
List myList=['香蕉','苹果','西瓜'];
myList.forEach((value){
   print("$value");
 });
 //2.map 根据条件对List进行修改
List myListMap=[1,3,4];      
var mapList=myListMap.map((value){
     return value*2;
});
print(mapList.toList()); //[2, 6, 8]
//3.where: 根据给定限定条件,过滤
List whereList=[1,3,4,5,7,8,9];
var newList=whereList.where((value){
   return value>5;
});
print(newList.toList());//[7, 8, 9]
//4.any: 只要集合里面有满足条件的就返回true
List anyList=[1,3,4,5,7,8,9];
var anyValue=anyList.any((value){   //只要集合里面有满足条件的就返回true
   return value>5;
});
print(anyValue);
//5.every: 每一个都满足条件返回true  否则返回false
List myList=[1,3,4,5,7,8,9];
var everyValue=myList.every((value){   //每一个都满足条件返回true  否则返回false
   return value>5;
});
print(everyValue);

6.2 Set

  • The main function of using it is to remove the duplicate content of the array
  • Set is an unordered and non-repeatable collection, so you cannot get the value through the index
 var s1=new Set();
  s1.add('香蕉');
  s1.add('苹果');
  s1.add('苹果');
  print(s1);   //{香蕉, 苹果}
  print(s1.toList()); //[香蕉, 苹果]
  List myList=['香蕉','苹果','西瓜','香蕉','苹果','香蕉','苹果'];
  var s2=new Set();
  s2.addAll(myList);
  print(s2);            //{香蕉, 苹果, 西瓜}
  print(s2.toList());   //[香蕉, 苹果, 西瓜]
  s2.forEach((value)=>print(value)));

6.3 Map

  • When the dictionary structure is in forEach, traverse the key-value
Map person={
  "name":"张三",
  "age":20
};
person.forEach((key,value){            
    print("$key---$value");
});
/*
name---张三
age---20
*/

Seven, function definition, optional parameters, default parameters, named parameters

7.1 Built-in methods/functions

    • Example: print();

7.2 Custom method:

    • The basic format of a custom method:
      返回类型  方法名称(参数1,参数2,...){
        方法体
        return 返回值;
      }
  • customize some methods
void printInfo() {
    print('一个自定义方法');
}
int getNumber(){
    var myNumber = 123;
    return myNumber;
}
String printUserInfo(){
    return 'this is string';
}
List getList(){
    return ['121','123','125'];
}
    • call custom method
printInfo();
var n = getNumber();
print(n);
print(printUserInfo());
print(getList());

7.3 Method scope

  • Method B can be defined inside method A, but method B can only be used within the scope of method A
void aMethod(){
    aaa(){
        print(getList());
        print('aaa');    
    }
    aaa();
}
//调用方法
aMethod();

7.4 Call method to pass parameters

7.4.1. Define a method to find the sum of all numbers from 1 to this number

int sumNum(int num){
    var sum = 0;
    for(var i = 1;i <= n;i++){
        sum += i;    
    }
    return sum;
}
var n1 = sumNum(5);
print(n1);
var n2 = sumNum(100);
print(n2);

7.4.2 Define a method and print user information

String printUserInfo(String username, int age){
    //行参
    return "姓名: $username --- 年龄: $age";
}
print(printUserInfo("张三",20));//实参

7.4.3 Defining a method with optional parameters

  • The latest dart defines optional parameters that need to specify a type default value
  • [int age] means age is an optional parameter
String printUserInfo(String username, [int age = 0]){//行参
    if (age != 0){
        return "姓名:$username --- 年龄: $age";    
    }
    return "姓名:$username --- 年龄保密";
}
print(printUserInfo("李四",28));
print(printUserInfo("王五"));

7.4.4 Defining a method with default parameters

  • In the optional parameter list, initialize the parameters.
String printUserInfo(String username,[String sex="男",int age=0]){//行参
    if (age != 0){
        return "姓名:$username --- 性别:$sex --- 年龄:$age";    
    }
    return "姓名:$username --- 性别: $sex --- 年龄保密";
}
print(printUserInfo("张三"));
print(printUserInfo("莉丝","女"));
print(printUserInfo("莉丝","女", 26));

7.4.5 Defining a method with named parameters

  • The latest dart defines named parameters that need to specify a type default value
String printUserInfo(String username,{int age = 0,String sex = '男'}){//行参
    if (age != 0){
        return "姓名:$username --- 性别: $sex --- 年龄: $age";    
    }
    return "姓名:$username --- 性别: $sex --- 年龄保密";
}
print(printUserInfo("钩陈",age: 20, sex: '未知'));

7.4.6 Implementing a method that takes a method as a parameter

  • Call the fn2 method and pass the fn1 method as a parameter.
var func=() {
    print("我是一个匿名方法");
};
func();
//fn1方法
fn1(){
    print("function one");
}
//fn2方法
fn2(func){
    func();
}
//调用fn2这个方法,把fn1这个方法当作参数传入.
fn2(fn1);
    • call result
我是一个匿名方法
fn1

8. Arrow functions, anonymous methods, closures

8.1 Arrow functions

  • Arrow functions are an abbreviated form of

Case 1:

  List list=['苹果','香蕉','西瓜'];
  list.forEach((value){
    print(value);
  });
  list.forEach((value)=>print(value));
  • Note the difference with the method: only one statement can be written in the arrow function, and there is no semicolon (;) after the statement
list.forEach((value)=>{
    print(value)
});

Case 2: Modify the data in the List below to multiply the values ​​greater than 2 in the array by 2

List list1 = [4,1,2,3,4];
var mapList1 = list1.map((value){
   if (value > 2){
       return value * 2;   
   } 
   return value;
});
print(mapList1.toList()); //[8, 1, 2, 6, 8]
var mapList2=list1.map((value)=> value > 2 ? value*2:value);
print(mapList2.toList());//[8, 1, 2, 6, 8]

Case 3:

  • 1. Define a method isEvenNumber to judge whether a number is even.
//1、定义一个方法isEvenNumber来判断一个数是否是偶数
bool isEvenNumber(int n){
    if (n % 2 == 0) {
        return true;    
    }
    return false;
}
  • 2. Define a method to print all even numbers within 1-n.
printNum(int n){
    for (var i = 1; i <= n; i++){
        if (isEvenNumber(i)) {
            print(i);        
        }    
    }
}
printNum(10);

8.2 Anonymous functions & self-executing methods & method recursion

  • First define a method to get an integer number
int getNum(int n){
    return n;
}
print(getNum(12));

8.2.1 Anonymous functions

  • A function of the form (){};
var printNumber = () {
  print(12345);  
};
printNumber();

8.2.2 Self-executing method

((int n){
    print(n*2);
    print("这是自执行方法");
})(123);

8.2.3 Method recursion

var suma = 1;
fua(int n){
    suma *= n;
    if (n == 1) {
        return;    
    }
    fna(n - 1);
}
fna(5);
print(suma);//1*2*3*4*5 = 120

Case 4: Find the sum of 1-100 through the recursion of the method

var sum = 0;
fn(int n){
    sum += n;
    if (n == 0) {
        return;    
    }
    fn(n-1);
}
fn(100);
print(sum);//5050

8.3 Closures

8.3.1 The origin of closure

  • 1. Features of global variables: global variables are resident in memory, and global variables pollute the whole world.
  • 2. The characteristics of local variables: non-resident memory will be recycled by the garbage mechanism, and will not pollute the whole world.
  • Want to achieve the function:

1. Permanent memory

2. Do not pollute the overall situation

  • Therefore, closures are generated, and closures can solve this problem.....
    • Closure: function nested function, the inner function will call the variables or parameters of the outer function, the variables or parameters will not be recycled by the system (the memory will not be released)
    • The way of writing the closure: the function nests the function, and returns the function inside, thus forming a closure.

8.3.2 Global variables

var a = 123;
void main(){
    print(a);
    func(){
        a++;
        print(a);    
    }
    func();//124
    func();//125
    func();//126
}

8.3.3 Local variables

printInfo(){
    var myNum = 234;
    myNum++;
    print(myNum);
}
printInfo();//235
printInfo();//235
printInfo();//235

8.3.4 Closures

funcClosure(){
    var a = 345;//不会污染全局,常驻内存
    return (){
        a++;
        print(a);    
    };
}
var para = funcClosure();
para();//346
para();//347
para();//348

Guess you like

Origin blog.csdn.net/SharkToping/article/details/130508858