Description:

This is a new beginning. Dart is a language that I think a lot of people know from the framework of Flutter, because Flutter is better known to us than Dart. A lot of people have been reluctant to try Flutter mostly because of the cost of learning the Flutter and obviously the need to learn a new language, DART, Then I went to study the development framework, Flutter, and there were a lot of craters, and judging by the number of issues of the Project on Github there were a lot of craters, so a lot of people were put off. Of course this is a problem that a new technical framework might have at first, but we need to see the cross-platform technical thinking of the Flutter framework.

Why start a series of articles about Dart?

In order to develop the Flutter, the core knowledge of using the Dart does not need to be too comprehensive. Some of the core knowledge of using the Dart does not need to be too comprehensive, so this series of articles will selectively cover some of the techniques that are commonly used in the Dart. On the other hand, for those of you who have read my article, I’m a big fan of Kotlin, but the language is the same, and you can see Kotlin in the Dart, so I can learn the Dart very quickly. So I’m going to compare the Dart to Kotlin for the next article on Dart, so if you’ve learned Kotlin, congratulations, you’re going to get into Dart pretty fast.

What will this series of Dart articles cover?

This series of articles covers the following topics: Dart basic syntax, variable constant and type derivation, collections, functions, object-oriented Mixins, generics, generator functions, Async and Await, Stream and Future, Isolate and EventLoop, and finally a basic introduction to how DartVM works.

A, Hello Dart

This is the first Hello Dart program. Most programs start with main, so Dart is no exception. Let’s take a look at the variations of main

// The standard writing of main
void main() {
  print('Hello World! ');Dart expressions end in a semicolon, just like Java expressions. If you're using Kotlin, this may be one of the biggest problems you'll have when you switch from Kotlin to Dart.
}

// All functions in dart can be omitted, returning type Dynamic when omitted
main() {
  print('Hello World! ');  
}

// If there is only one expression inside the function, omit the braces and use "=>" to arrow the function;
Fun main(args: Array
      
       ) = println('Hello World! ')
      
void main() => print('Hello World! ');

// Short form
main() => print('Hello World! ');
Copy the code

2. Data types

Everything in Dart is an Object, including numbers, booleans, functions, and so on. They all inherit from Object as Java does, so their default value is null. Dart has the following types: bool, num(int, double, num), String, List, Set, Map, Runes and Symbols.

1. Boolean type (bool)

Dart uses bool to declare a Boolean variable or constant, just like C does, and Kotlin uses Boolean to declare a Boolean variable or constant, but consistently it only has two true and false values.

main() {
    bool isClosed = true;Dart also uses the [type][variable name] declaration, which is different from Kotlin's [variable name]:[type] declaration.
    bool isOpened = false;
}
Copy the code

2, numeric type (num, int, double)

In dart, num, int, and double are classes, and then int and double inherit from the num abstract class. This is similar to Kotlin, where Number, int, and double are classes, and then int and double inherit from Number. Note, however, that there are no float, short, or long types in Dart

! [](/Users/mikyou/Library/Application Support/marktext/images/2019-10-24-22-02-40-image.png)

main() {
    double pi = 3.141592653;
    int width = 200;
    int height = 300;
    print(width / height);// Int = double; // Int = double; // Int = double;
    print(width ~/ height);// Note: This is the correct position for the dart
}
Copy the code

Dart, like Java and Kotlin, also has a number of functions:

main() {
    print(3.141592653.toStringAsFixed(3)); //3.142 Keep valid digits
    print(6.6.floor());//6 is rounded down
    print((6.6).ceil()); //-6 is rounded up
    print(9.9.ceil()); //10 is rounded up
    print(666.6.round()); //667 rounding
    print((666.6).abs()); // 666.6 Take the absolute value
    print(666.6.toInt()); //666 is converted toInt, where toInt, toDouble and Kotlin are similar
    print(999.isEven); //false Is an even number
    print(999.isOdd); // True Whether it is odd
    print(666.6.toString()); //666.6 Convert to string
}
Copy the code

3, String type (String)

Dart supports single, double, triple, and $string templates the same way Kotlin does.

main() {
    String name = 'Hello Dart! ';/ / single quotation marks
    String title = "'Hello Dart! '";/ / double quotation marks
    String description = """ Hello Dart! Hello Dart! Hello Dart! Hello Dart! Hello Dart! "" ";/ / three quotes
    num value = 2;
    String result = "The result is $value";// Single-value reference
    num width = 200;
    num height = 300;
    String square = "The square is ${width * height}";// The value reference of the expression
}
Copy the code

Dart, like Kotlin, has many ways to manipulate strings, such as string splitting, substrings, and so on

main() {
  String url = "https://mrale.ph/dartvm/";

  print(url.split(": / /") [0]); // String split method, similar to Java and Kotlin

  print(url.substring(3.9)); // String interception substring method, similar to Java and Kotlin

  print(url.codeUnitAt(0)); // Take the utF-16 code of the current index position character

  print(url.startsWith("https")); // Whether the current string starts with the specified character, similar to Java and Kotlin

  print(url.endsWith("/")); // Whether the current string ends with the specified character, similar to Java and Kotlin

  print(url.toUpperCase()); // Uppercase, similar to Java and Kotlin

  print(url.toLowerCase()); // Lowercase, similar to Java and Kotlin

  print(url.indexOf("ph")); // Get the index position of the specified character, similar to Java and Kotlin

  print(url.contains("http")); // Whether the string contains specified characters, similar to Java and Kotlin

  print(url.trim()); // Remove the first and last Spaces of the string, similar to Java and Kotlin

  print(url.length); // Get the string length

  print(url.replaceFirst("t"."A")); // Replace the character where the t character first appears

  print(url.replaceAll("m"."M")); // Replace all, similar to Java and Kotlin
}
Copy the code

4. Type checking (is and IS!) And cast (as)

Dart, like Kotlin, checks types using the IS keyword and casts them using the as keyword. If it’s not a certain type, dart uses is! In Kotlin, the exact opposite is used! Is said.

main() {
    int number = 100;
    double distance = 200.5;
    num age = 18;
    print(number is num);//true
    print(distance is! int);//true
    print(age as int);/ / 18
}
Copy the code

5. Runes and Symbols types

The Runes and Symbols types are not used much in Dart. For a brief introduction, the Runes type is a Unicode string defined as utF-32 byte units. Unicode can use numbers to represent letters, numbers, and Symbols. However, in DART a String is a series of UTF-16 bytes, so to represent 32-bit Unicode values, you need to use the Runes type. We typically use the form \uxxxx to represent a Unicode code, where XXXX represents four hexadecimal values. When the hexadecimal data is too many or less than four bits, put the hexadecimal number in curly braces, for example, the smiley emoji (😆) is \u{1f600}. The Symbols type is used less frequently and is generally used for reflections in Dart, but note that reflections are not allowed in Flutter.

main() {
  var clapping = '\u{1f44f}';
  print(clapping);
  print(clapping.codeUnits);// Return a 16-bit array of character units
  print(clapping.runes.toList());

  Runes input = new Runes(
      '\u2665 \u{1f605} \u{1f60e} \u{1f47b} \u{1f596} \u{1f44d}');
  print(new String.fromCharCodes(input));
}
Copy the code

6. Type Object

Everything in Dart is an Object, inherited from Object, so you can use Object to define any variable, and the type can change after assignment.

main() {
    Object color = 'black';
    color = 0xff000000;// It works fine. The 0xFF000000 type is int, and int also inherits from Object
}
Copy the code

7. Dynamic

Dart has another type that is very similar to Object and that is the dynamic type. The var type is dynamic when the variable is not assigned. It can change its type just like Object. Dynamic is used when the specific type cannot be determined. Note: It is recommended that you do not abuse dynamic and generally use Object. If you are familiar with Flutter and Native Communication PlatformChannel code, You’ll see a lot of use of Dynamic, because maybe the native data type doesn’t match the data type in dart, so dart will generally use Dynamic.

The difference between Object and dynamic is that Object checks the type during compilation, whereas dynamic does not check the type during compilation.

main() {
    dynamic color = 'black';
    color = 0xff000000;// It works fine. The 0xFF000000 type is int, and int also inherits from Object
}
Copy the code

Variables and constants

1. The var keyword

Dart can use var instead of declaring a specific type. The type of the variable is automatically derived. This is because var is not a direct value, but an object reference that stores the value, so var can declare any variable. This is different from Kotlin, where variable declarations must be made using the var keyword. The type derivation of Kotlin is that the default behavior is not directly related to var. Note: Variables are often declared with VAR during Flutter development so that the types of variables can be derived automatically.

main() {
  int colorValue = 0xff000000;
  var colorKey = 'black'; //var specifies that a variable is automatically derived as a String based on the type of the assigned value
  // Use var to declare collection variables
  var colorList = ['red'.'yellow'.'blue'.'green'];
  var colorSet = {'red'.'yellow'.'blue'.'green'};
  var colorMap = {'white': 0xffffffff.'black': 0xff000000};
}
Copy the code

However, when using var to declare a variable, it is important to note that if the variable is not initialized initially, not only the value can be changed but also its type can be modified. Once the initialization is started, the type is determined and cannot be changed.

main() {
  var color; // The type of color is dynamic, so its type can be changed
  color = 'red';
  print(color is String); //true 
  color = 0xffff0000;
  print(color is int); //true 

  var colorValue = 0xffff0000; // In this case, the colorValue type has been derived to int and the type has been determined
  colorValue = 'red'; // Error, where a compilation exception is thrown. A String value cannot be assigned to an int
  print(colorValue is int); //true
}
Copy the code

2. Constants (final and const)

You can declare constants in Dart using either const or final keywords. Note: The difference between the two is that if the constant is initialized at compile time we use const(similar to the const val in Kotlin) and if the constant is initialized at run time we use final(similar to the val in Kotlin)

main() {    
  const PI = 3.141592653;// Const
  final nowTime = DateTime.now();// Final defines constants
}
Copy the code

4, Set (List, Set, Map)

1, set List

In other words, the dart set type system is divided differently from Kotlin’s. For example, there is no strict distinction between a List in Kotlin’s List and a MutableList in dart. It’s more like an array in the way it’s used, but you can add or delete elements at will.

  • List Indicates the initialization mode

    main() {
        List<String> colorList = ['red'.'yellow'.'blue'.'green'];// Use the [] form directly to initialize
        var colorList = <String> ['red'.'yellow'.'blue'.'green'];
    }
    Copy the code
  • List of common functions

    main() {
        List<String> colorList = ['red'.'yellow'.'blue'.'green'];
        colorList.add('white');// Add a new element like Kotlin
        print(colorList[2]);// We can use array subscripts to access elements
        print(colorList.length);// Get the length of the set. Kotlin uses size instead
        colorList.insert(1.'black');// Insert the specified element at the specified index position in the collection
        colorList.removeAt(2);// Remove the third element from the set with index=2
        colorList.clear();// Clear all elements
        print(colorList.sublist(1.3));// Intercept the subset
        print(colorList.getRange(1.3));// Get a range element in the collection
        print(colorList.join('< -- - >'));JoinToString: red<-- >yellow<-- >blue<-- >green
        print(colorList.isEmpty);
        print(colorList.contains('green'));    
    }
    Copy the code
  • List traversal

    main() {
        List<String> colorList = ['red'.'yellow'.'blue'.'green'];
        / / for the -i traversal
        for(var i = 0; i < colorList.length; i++) {// You can use var or int
            print(colorList[i]);        
        }
        / / forEach traversal
        colorList.forEach((color) => print(color));//forEach takes Function. => Uses arrow Function
        / / the for - the in traverse
        for(var color in colorList) {
            print(color);
        }
        // While +iterator iterator traversal, similar to Java iteator
        while(colorList.iterator.moveNext()) {
            print(colorList.iterator.current); }}Copy the code

2

The difference between a Set and a List is that the elements in a Set cannot be repeated. So adding duplicate elements returns false, indicating that the addition was unsuccessful.

  • Set Specifies the initialization mode

    main() {
        Set<String> colorSet= {'red'.'yellow'.'blue'.'green'};// Initialize with {} form
        var colorList = <String> {'red'.'yellow'.'blue'.'green'};
    }
    Copy the code
  • In Kotlin, there is no API for calculating intersection, union and complement of sets

    main() {
        var colorSet1 = {'red'.'yellow'.'blue'.'green'};
        var colorSet2 = {'black'.'yellow'.'blue'.'green'.'white'};
        print(colorSet1.intersection(colorSet2));{'yellow', 'blue', 'green'}
        print(colorSet1.union(colorSet2));/ / and set - > output: {' black ', 'red', 'yellow', 'blue', 'green', 'white'}
        print(colorSet1.difference(colorSet2));// add --> output: {'red'}
    }
    Copy the code
  • Set traversal (same as List)

      main() {
        Set<String> colorSet = {'red'.'yellow'.'blue'.'green'};
        / / for the -i traversal
        for (var i = 0; i < colorSet.length; i++) {
          // You can use var or int
          print(colorSet[i]);
        }
        / / forEach traversal
        colorSet.forEach((color) => print(color)); //forEach takes Function. => Uses arrow Function
        / / the for - the in traverse
        for (var color in colorSet) {
          print(color);
        }
        // While +iterator iterator traversal, similar to Java iteator
        while (colorSet.iterator.moveNext()) {
          print(colorSet.iterator.current); }}Copy the code

3, set Map

The set Map is similar to Kotlin in that it is stored in the key-value form, and the key in the Map object cannot be repeated

  • Map initialization mode

    main() {
        Map<String.int> colorMap = {'white': 0xffffffff.'black':0xff000000};// Initialize with {key:value}
     var colorMap = <String.int> {'white': 0xffffffff.'black':0xff000000};
    }
    Copy the code
  • Functions commonly used in Map

    main() {
        Map<String.int> colorMap = {'white': 0xffffffff.'black':0xff000000};
        print(colorMap.containsKey('green'));//false
        print(colorMap.containsValue(0xff000000));//true
        print(colorMap.keys.toList());//['white','black']
        print(colorMap.values.toList());//[0xffffffff, 0xff000000]
        colorMap['white'] = 0xfffff000;// Modify the element of the specified key
        colorMap.remove('black');// Remove the element with the specified key
    }
    Copy the code
  • Traversal mode of Map

    main() {
        Map<String.int> colorMap = {'white': 0xffffffff.'black':0xff000000};
        //for-each key-value
        colorMap.forEach((key, value) => print('color is $key, color value is $value'));
    }
    Copy the code
  • Map. FromIterables converts a List collection to a Map

    main() {
        List<String> colorKeys = ['white'.'black'];
        List<int> colorValues = [0xffffffff.0xff000000];
        Map<String.int> colorMap = Map.fromIterables(colorKeys, colorValues);
    }
    Copy the code

4, the collection of common operators

Dart is also very modern in its approach to set operations, with a rich set operator API that makes it easier to work with structured data.

main() {
  List<String> colorList = ['red'.'yellow'.'blue'.'green'];
  //forEach arrow function traversal
  colorList.forEach((color) => {print(color)});
  colorList.forEach((color) => print(color)); If there is only one expression inside the arrow function, the braces can be omitted

  // Use the map function
  print(colorList.map((color) => '$color_font').join(","));

  // The return value of each element is true/false
  print(colorList.every((color) => color == 'red'));

  // Use of the sort function
  List<int> numbers = [0.3.1.2.7.12.2.4];
  numbers.sort((num1, num2) => num1 - num2); // Sort in ascending order
  numbers.sort((num1, num2) => num2 - num1); // Sort in descending order
  print(numbers);

  // The where function is used, which is equivalent to the filter operator in Kotlin and returns a set of elements that match the condition
  print(numbers.where((num) = >num > 6));

  // The firstWhere function, equivalent to the find operator in Kotlin, returns the first element that matches the condition, or null if none is found
  print(numbers.firstWhere((num) = >num= =5, orElse: () => - 1)); // Note: If it is not found, execute the orElse block and return a specified default value

  // Use the singleWhere function to return the first element that matches the condition, or null if it is not found, but only if there is one element in the set that matches the condition, otherwise an exception will be thrown
  print(numbers.singleWhere((num) = >num= =4, orElse: () => - 1)); // Note: If it is not found, execute the orElse block and return a specified default value

  Take (n) means to take the first n elements of the current set, skip(n) means to skip the first N elements, and then take all the remaining elements
  print(numbers.take(5).skip(2));

  // The use of the list. from function to create a new set from a given set, equivalent to clone a set
  print(List.from(numbers));

  // Expand a set of elements into multiple elements, or expand a two-dimensional array of elements into a tiled one-bit array
  var pair = [
    [1.2],
    [3.4]].print('flatten list: ${pair.expand((pair) => pair)}');

  var inputs = [1.2.3];
  print('duplicated list: ${inputs.expand((number) =>[ number, number, number ])}');
}
Copy the code

V. Process control

1, for loop

main() {
    List<String> colorList = ['red'.'yellow'.'blue'.'green'];
    for (var i = 0; i < colorList.length; i++) {// You can use var or int
        print(colorList[i]); }}Copy the code

2, while loop

main() {
    List<String> colorList = ['red'.'yellow'.'blue'.'green'];
    var index = 0;
    while (index < colorList.length) {
        print(colorList[index++]); }}Copy the code

3. Do-while loop

main() {
    List<String> colorList = ['red'.'yellow'.'blue'.'green'];
    var index = 0;
    do {
        print(colorList[index++]);
    } while (index < colorList.length);
}
Copy the code

4, break and continue

main() {
    List<String> colorList = ['red'.'yellow'.'blue'.'green'];
    for (var i = 0; i < colorList.length; i++) {// You can use var or int
        if(colorList[i] == 'yellow') {
            continue;
        }
        if(colorList[i] == 'blue') {
            break;
        }
        print(colorList[i]); }}Copy the code

5, if – else

void main() {
  var numbers = [1.2.3.4.5.6.7.8.9.10.11];
  for (var i = 0; i < numbers.length; i++) {
    if (numbers[i].isEven) {
      print('even number:${numbers[i]}');
    } else if (numbers[i].isOdd) {
      print('the odd number:${numbers[i]}');
    } else {
      print('Illegal numbers'); }}}Copy the code

6. The ternary operator (? 🙂

void main() {
  var numbers = [1.2.3.4.5.6.7.8.9.10.11];
  for (var i = 0; i < numbers.length; i++) {
      num targetNumber = numbers[i].isEven ? numbers[i] * 2 : numbers[i] + 4;
      print(targetNumber); }}Copy the code

7. Switch-case statement

Color getColor(String colorName) {
  Color currentColor = Colors.blue;
  switch (colorName) {
    case "read":
      currentColor = Colors.red;
      break;
    case "blue":
      currentColor = Colors.blue;
      break;
    case "yellow":
      currentColor = Colors.yellow;
      break;
  }
  return currentColor;
}
Copy the code

8. Assert

In DART, you can use an assert statement to break the execution of your code if the result of a condition expression does not satisfy the condition. In particular, the Flutter source code is littered with the use of assert assertions. Note: Assertions are valid only when run in check mode, and will not be executed if run in production mode.

assert(text ! =null);// If text is null, subsequent code execution will be interrupted
assert(urlString.startsWith('https'));
Copy the code

Operator

1. Arithmetic operators

The name of the The operator example
add + var result = 1 + 1;
Reduction of var result = 5 – 1;
take * var result = 3 * 5;
In addition to / var result = 3 / 5; / / 0.6
aliquot ~ / var result = 3 ~/ 5; / / 0
Take more than % var result = 5 % 3; / / 2

2. Conditional operators

The name of the The operator example
Is greater than > 2 > 1
Less than < 1 < 2
Is equal to the = = 1 = = 1
Is not equal to ! = 3 != 4
Greater than or equal to > = 5 > = 4
Less than or equal to < = 4 < = 5

3. Logical operators

The name of the The operator example
or || < 1 > 1 | 2 | 3
with && 2 > 1 && 3 < 1
non ! ! (2 > 1)

4. Bitwise operators

The name of the The operator
with &
or |
A non ~
Exclusive or ^
Shift to the left <<
Moves to the right >>

5. Ternary operators

condition ? expr1 : expr2

var isOpened = (value == 1)?true : false;
Copy the code

6, empty security operator

The operator explain
result = expr1 ?? expr2 If expr1 is null, return the value of expr2; otherwise, return the value of expr1
expr1 ?? = expr2 If expr1 is null, the value of expr2 is assigned to expr1
result = expr1? .value If expr1 is null, return null, otherwise return the value of expr1.value
  • 1、result = expr1 ?? expr2

    If expr1 is null, return the value of expr2, otherwise return the value of expr1. This is similar to result = expr1? : expr2

    main() {
        var choice = question.choice ?? 'A';
        / / equivalent to the
        var choice2;
        if(question.choice == null) {
            choice2 = 'A';
        } else{ choice2 = question.choice; }}Copy the code
  • 2, expr1?? = expr2 is equivalent to expr1 = expr1?? Expr2 (convert to the first)

    main() {
        varchoice ?? ='A';
        / / equivalent to the
        if(choice == null) {
            choice = 'A'; }}Copy the code
  • 3, result = expr1? .value

    If expr1 is not null then return expr1.value, otherwise return null, as in Kotlin? If expr1 is not null, the latter is executed

    varchoice = question? .choice;/ / equivalent to the
    if(question == null) {return null;
    } else {
        returnquestion.choice; } question? .commit();/ / equivalent to the
    if(question == null) {return;// Do not commit()
    } else {
        question.commit();// Execute the commit method
    }
    Copy the code

7. Cascading operators (..)

The cascading operators are.. , lets you chain calls to fields in an object, similar to the apply or run functions in Kotlin.

question .. id ='10001'
    ..stem = 'Question 1: XXXXXX'
    ..choices = <String> ['A'.'B'.'C'.'D']
    ..hint = 'Listen to the audio and do the problem';
Copy the code

The run function in Kotlin implements the comparison

question.run {
    id = '10001'
    stem = 'Question 1: XXXXXX'
    choices = listOf('A'.'B'.'C'.'D')
    hint = 'Listen to the audio and do the problem'    
}
Copy the code

Operator overloading

Custom operator overloading is supported in DART. Overloaded functions are defined using the operator keyword

class Vip {
  final int level;
  final int score;

  const Vip(this.level, this.score);

  bool operator >(Vip other) =>
      level > other.level || (level == other.level && score > other.score);

  bool operator <(Vip other) =>
      level < other.level || (level == other.level && score < other.score);

  bool operator ==(Vip other) =>
      level == other.level &&
      score == other.level; // Note: This code may report an error in higher versions of Dart, but is OK in earlier versions
  == == == == == == == == == == =
  @override
  bool operator ==(covariant Vip other) =>
      (level == other.level && score == other.score);

  @override
  int get hashCode => super.hashCode; // Along the way, you need to rewrite the hashCode
}


main() {
    var userVip1 = Vip(4.3500);
    var userVip2 = Vip(4.1200);
    if(userVip1 > userVip2) {
        print('userVip1 is super vip');
    } else if(userVip1 < userVip2) {
        print('userVip2 is super vip'); }}Copy the code

Seven, abnormal

Dart uses a try-catch-finally method similar to Java and Kotlin. Use the ON keyword to catch specific exceptions. Common exceptions in dart are: NoSuchMethodError(raised when a function that is not implemented on an object is called), and ArgumentError (raised when a function is called with an incorrect argument)

main() {
  int num = 18;
  int result = 0;
  try {
    result = num~ /0;
  } catch (e) {/ / capture IntegerDivisionByZeroException
    print(e.toString());
  } finally {
    print('$result'); }}// Use the on keyword to catch specific exceptions
main() {
  int num = 18;
  int result = 0;
  try {
    result = num~ /0;
  } on IntegerDivisionByZeroException catch (e) {// Catch specific exceptions
    print(e.toString());
  } finally {
    print('$result'); }}Copy the code

Eight, functions,

Functions are as important in Dart as objects, with support for closures and higher-order functions, and dart’s functions are much more flexible than Java’s, and Kotlin’s functions are even more comprehensive than Kotlin’s. For example, default parameters, optional parameters, and named parameters are supported.

1. Basic usage of functions

main() {
    print('sum is ${sum(2.5)}');
}

num sum(num a, num b) {
    return a + b;
}
Copy the code

2, function parameter list parameter passing rules

// Num a, num B, num C, num d the most common parameters: the number and order of parameters must be fixed
add1(num a, num b, num c, num d) {
  print(a + b + c + d);
}

//[num a, num B, num c, num d] Parameter passing: The number of parameters is not fixed during the call, but the sequence of parameters must be one-to-one. Named parameters are not supported
add2([num a, num b, num c, num d]) {
  print(a + b + c + d);
}

//{num a, num b, num c, num d} Pass parameters: The number of parameters can be variable and the order of parameters can be variable when called. Named parameters, also known as optional parameters, are a feature of DART. This is why the Flutter code has so many optional attributes and uses a lot of optional parameters
add3({num a, num b, num c, num d}) {
  print(a + b + c + d);
}

//num a, num b, {num c, num d} {num c, num d
add4(num a, num b, {num c, num d}) {
  print(a + b + c + d);
}

main() {
  add1(100.100.100.100); // The most common parameter pass: the number and order of parameters must be fixed when calling
  add2(100.100); // When called, the number of parameters is not fixed, but the order of the parameters must be one to one. Named parameters are not supported (which means the order is not changed).
  add3(
      b: 200,
      a: 200,
      c: 100,
      d: 100); // When called, the number of parameters is not fixed, and the order of parameters can also be fixed. Named parameters are supported (which means the order can be variable).
  add4(100.100, d: 100, c: 100); // When called, the number of parameters a and b is fixed and the order is determined, and the number and order of parameters C and D can also be unfixed
}
Copy the code

3. Default and optional function arguments (and comparisons with Kotlin)

Dart’s default and optional parameters are the same as Kotlin’s default and named parameters, but they are written differently

add3({num a, num b, num c, num d = 100{})//d is the default parameter and is given a default value of 100
   print(a + b + c + d);
}

main() {
    add3(b: 200, a: 100, c: 800);
}
Copy the code

Compared with Kotlin

fun add3(a: Int, b: Int, c: Int, d: Int = 100) {
    println(a + b + c + d)
}

fun main(args: Array<String>) {
    add3(b = 200, a = 100, c = 800)}Copy the code

4. Function types and higher-order functions

The dart Function is also a type Function that can be passed as a Function argument or as a return value. Similar to the FunctionN series of functions in Kotlin

main() {
  Function square = (a) {
    return a * a;
  };

  Function square2 = (a) {
    return a * a * a;
  };

  add(3.4, square, square2)
}

num add(num a, num b, [Function op, Function op2]) {
  // Functions are passed as arguments
  return op(a) + op2(b);
}
Copy the code

5. Simplification of functions and arrow functions

In Dart, if you have only one expression in the body of the function, you can use arrow functions to simplify the code, which is similar to Kotlin, except that in Kotlin they call lambda expressions, but in a different way.

add4(num a, num b, {num c, num d}) {
  print(a + b + c + d);
}

add5(num a, num b, {num c, num d})  =>  print(a + b + c + d);
Copy the code

Object oriented

Everything is an object in Dart, so object orientation is still important in Dart. Let’s take a look at object orientation in Dart with a simple example, and we’ll go further.

1. Basic definition and use of classes

abstract class Person {
    String name;
    int age;
    double height;
    Person(this.name, this.age, this.height);// This is actually a syntactic sugar for Dart. But it's not as good as Kotlin, where you skip the whole this.name thing.
    // This is the equivalent of the above code, which is mandatory in Java
    Person(String name, int age, double height) {
        this.name = name;
        this.age = age;
        this.height = height;
    }   
    // However, Kotlin is very thorough. You only need to declare the properties
    abstract class Person(val name: String.val age: Int.val height: Double)}class Student extends Person {// Use the extends keyword to indicate inheritance as in Java
    Student(String name, int age, double height, double grade): super(name, age, height);// In Dart: class name (variable, variable...) Is how the constructor is written. :super() means that the constructor calls the superclass, passing three arguments to the constructor
}
Copy the code

2. Getter and setter accessors for class properties (similar to Kotlin)

abstract class Person {
  String _name; The variable //// is equivalent to the var modifier in Kotlin. It has setter and getter accessors, but it does not have access in dart. By default, variables starting with _ _ indicate private permissions, and external files are not accessible
  final int _age;// A variable equivalent to the val in kotlin has only getter accessors
  Person(this._name, this._age); // This is the short form of the above

  // Calculate a custom setter accessor for a property using the set keyword
  set name(String name) => _name = name;
  // Calculate a custom getter accessor for a property using the get keyword
  bool get isStudent => _age > 18;
}
Copy the code

conclusion

This is the first article on Dart, and it basically introduces the syntax of DART in general, although there are a few more things that need to be explored, and we’ll explore them later. If you look at the Kotlin and Dart syntax as a whole, there are a lot of features that are features of modern programming languages, including those you see in other languages such as Swift. With that, let’s move on to dart and flutter…

My official account

Here are the latest Articles on Dart, Flutter and Kotlin, as well as excellent translations of foreign articles