Dart (2)–function & operator & conditional statement & exception

Article directory

      • 1. Function
        • 1. Define the function
          • 1.1 => single-line expression
        • 2. Parameters
          • 2.1 {} named parameters
          • 2.2 [] positional parameters
          • 2.3 Parameter default values
        • 3. Function passing
        • 4. Anonymous functions
      • Second, the operator
        • 1. Arithmetic operators
        • 2. Relational operators
        • 3. Type judgment operator
        • 4. Assignment operator
          • 4.1 = nullable variable assignment
          • 4.2 Other assignment operators
        • 5. Logical operators
        • 6. Bitwise and shift operators
        • 7. Conditional Operators
          • 7.1 Condition ? Expression1 : Expression2
          • 7.2 Expression 1 Expression 2
        • 8. Cascading operators
          • 8.1..
          • 8.2 ?..
        • 9. Other operators
      • Three, conditional statement
        • 1.assert assertion
      • 4. Abnormal
        • 1. Throw an exception
        • 2. Catch exceptions
          • 2.1 catch
          • 2.2 on
        • 3. Rethrow

The previous article introduced how Dart defines variables and its built-in types. This article will introduce how to define functions, various operators, and conditional statements

1. Function

Dart’s function is similar to kotlin, and it is also an object. The function can be passed as a parameter or returned as a parameter.

1. Define function

The rules for defining functions in Dart are: [return type] ([parameter type] parameter name, ...){ return return value}, it can be seen that return type< is inferred from the type of Dart /code> and parameter type can be omitted, but it is officially recommended to write in full

// Define a sum function
int sum(int a, int b) {<!-- -->
  return a + b;
}

main() {<!-- -->
  print(sum(10, 20));
}
1.1 => Single line expression

If your function only has a simple expression, you can use => instead of {}

// Define a sum function
int sum(int a, int b) => a + b;

main() {<!-- -->
  print(sum(10, 20));
}

2. Parameters

Dart's parameter definition is very flexible, and there are also optional parameters and parameter default values

2.1 {} named parameters

In addition to the above method of passing parameters when defining a function, Dart also supports optional parameters, one of which is a named parameter

Named parameters are defined using the {parameter1,parameter2,...} rule and must be placed after the required parameters. Non-require-modified nullable named parameters or optional parameters have default values when calling, you can not pass a value, or you can use parameter name: for named parameters code> to specify the value. When passing named parameters, they can be placed anywhere

// Define a sum function with optional parameters
int sum(int a, {<!-- -->int? b}) {<!-- -->
  if (b != null) return a + b;
  return a;
}

main() {<!-- -->
  print(sum(10));
  // Specify parameter b as 10
  print(sum(10, b: 10));
  // When the named parameter is passed, it can be placed in any position
  print(sum(b: 20, 30));
}

operation result:

If you want to set a named parameter as required, you can use the require keyword to modify the parameter. However, because it is already an optional parameter when it is defined, there are not many usage scenarios for require

// Define a sum function with optional parameters
int sum(int a, {<!-- -->required int? b}) {<!-- -->
  if (b != null) return a + b;
  return a;
}

If the value of parameter b is not passed at this time, an error will be reported:

2.2 [] positional parameters

Another optional parameter is a positional parameter, which is less functional than a named parameter. It cannot specify a value with a parameter name, cannot use require to modify it, and cannot place and pass parameter positions at will.

// print with prefix
prefixPrint(String info, [String? prefix]) {<!-- -->
  if (prefix != null) return print(prefix + info);
  print(info);
}

main() {<!-- -->
  prefixPrint("info", "hi");
}
2.3 Parameter default values

We can set default values for optional parameters, just use = to assign values directly when defining, the default value must be a constant, named parameter require modification and parameter default value cannot be at the same time use

// print information defaults to hi
hiPrint({<!-- -->String info = "hi"}) => print(info);

main() {<!-- -->
  hiPrint(info: "hello");
  hiPrint();
}

operation result:

// print with prefix
prefixPrint(String info, [String prefix = ""]) {<!-- -->
  return print(prefix + info);
}

main() {<!-- -->
  prefixPrint("info", "hi");
  prefixPrint("info");
}

operation result:

3. Function passing

As mentioned above, a function in Dart is also an object, which can be assigned to a variable and passed as a parameter

// define function
void hi() => print("hi");

// The action parameter is a function, which is called once before printing
void combinePrint(String info, void action()) {<!-- -->
  action();
  print(info);
}

main() {<!-- -->
  // assign function to variable
  var printHi = hi;
  // call function variable
  printHi();

  combinePrint("Call hi function before printing", hi);
}

operation result:

4. Anonymous function

Functions can also be created anonymously, similar to how functions are defined

The following program is a bit boring. We define a named function callFunction, which has three parameters, which are int type a and b, and A function parameter function that receives two int value parameters, we pass the a, b parameters of callFunction Used for the function function to get the value and print it.

When calling callFunction, we used an anonymous function

// call the function of the function parameter
void callFunction(int a, int b, int function(int a, int b)) {<!-- -->
  // The incoming a, b, passed to the function
  var result = function(a, b);
  // print the result
  print(result);
}

main() {<!-- -->
  // pass in an anonymous function
  callFunction(10, 20, (a, b) {<!-- -->
    return a - b;
  });
}

operation result:

If the anonymous function only has a single-line expression, it also supports => definition:

main() {<!-- -->
  // pass in an anonymous function
  callFunction(10, 20, (a, b) {<!-- -->
    return a - b;
  });

  callFunction(10, 20, (a, b) => a + b);
}

Second, operator

Dart operators are similar to conventional ones, and the list is directly listed below for quick browsing

1. Arithmetic operators

Difference: / is division and returns a double type; ~/ is rounding

operator description
+ add
- minus
* multiply
/ divide
~/ rounding
% modulo
+ + Number + 1, the front returns the current Number + 1, back to return the current number
-- number -1, front to return the current number -1 , the post returns the current number

2. Relational operators

operator description
== equal
!= not equal
greater than
< less than
>= greater than or equal to
<= Less than or equal to

3. Type judgment operator

operator description
as Type conversion (also used as specified library prefix))
is if object If it is the specified type, return true
is! If the object is the specified type, return false

4. Assignment operator

4.1 = Nullable variable assignment

Due to the existence of empty variables in Dart, in addition to directly using = to assign values to non-empty variables, you can also use = to assign values to empty variables, which will be in the variable The assignment operation is performed when it is empty, and no assignment is performed when it is not empty

main() {<!-- -->
  int? i;
  i = 1;
  i = 2;

  print(i);
}

When assigning a value to a nullable variable that is not empty, a warning will be reported, and the running result is:

4.2 Other assignment operators
operator description
= Assignment
*= Assign after multiplication
%= Assign after modulus
>>= Assignment after right shift
>>>= Assignment after unsigned right shift
^= Exponential assignment
+ = Assignment after addition
/= Assignment after removal
<<= Assign after left shift
<<<= Assign after unsigned left shift
& amp;= Assign after and
` =`
-= Assignment after subtraction
~/= Assignment after rounding

5. Logical operators

operator description
!*expression * Reverse the result of the expression (i.e. true to false, false to true)
|| Logical OR
& amp; & amp; Logical AND

6. Bitwise and shift operators

7. Conditional operator

In addition to the ternary operator, Dart also has a null operator

7.1 Condition ? Expression 1 : Expression 2

If the condition is true, execute expression 1 and return the execution result, otherwise execute expression 2 and return the execution result.

7.2 Expression 1 Expression 2

If expression1 is not null return its value, otherwise execute expression2 and return its value.

8. Cascade operator

The cascading operator is also convenient for configuring variables, but it is not as easy to use as kotlin's functional programming

8.1 ...

..: Continuously call variables or methods of multiple objects on the same object, pay attention to ; when using only one

class P {<!-- -->
  var name;
  var password;
}

main() {<!-- -->
  var p = P()
    ..name = "zhangsan"
    ..password = "123";

  print(p.name);
  print(p.password);
}

operation result:

8.2?..

If the object may be empty, use ?.. to operate when it is not empty

class P {<!-- -->
  var name;
  var password;
}

// return an empty
P? getP() {<!-- -->}

main() {<!-- -->
  var p = getP()
    ?..name = "zhangsan"
    ..password = "hi";

  print(p);
}

operation result:

9. Other operators

operator description
& amp; Bitwise AND
| Bitwise OR
^ Bitwise XOR
~*expression* Bitwise inversion (that is, "0" becomes "1", "1" becomes "0")
<< bit left
>> bit right shift
>>> unsigned right shift
operator name description
() Using method Represents calling a method
[] Access List Access elements at specific positions in List
?[] Empty access to the List When the caller on the left is not empty, access the element at a specific position in the List
. Access members Member accessors
?. Conditional access member Similar to the above member accessor, but the operation object on the left cannot be null, such as foo?.bar, if foo is null, return null, otherwise return bar
! The null assertion operator converts the type of the expression to its underlying type if A runtime exception is thrown if the conversion fails. For example foo!.bar, if foo is null, a runtime exception is thrown

Three, conditional statement

Dart conditional statements are almost the same as Java

  • if and else: else is optional
  • for loop: iterable objects support: for(i in iterator)
  • while and do-while loops
  • break and continue
  • switch and case: case still needs to cooperate with break, use == to compares integers, strings, or compile-time constants

1.assert assertion

Assertion uses assert(expression), if the expression is true, the program continues to execute, otherwise an AssertionError exception is thrown. In Flutter, debug mode assertions work, but in production code, assertions are ignored

Fourth, Abnormal

Unlike Java, all exceptions in Dart are unchecked exceptions, methods don't have to declare which exceptions will be thrown, and you don't have to catch any exceptions.

1. Throw an exception

In addition to throwing a specific Exception and Error two types of exceptions:

throw FormatException('Expected at least 1 section');

Dart is also free to throw an object as an exception:

throw "hi";

2. Catch exception

2.1 catch

Conventional try-catch-finally way:

main() {<!-- -->
  var i;

  try {<!-- -->
    assert(i != null);
  } catch (e) {<!-- -->
    print(e);
  } finally {<!-- -->
    print("finally");
  }

  print("next..");
}

operation result:

catch also supports the second parameter, which is the stack information StackTrace object:

main() {<!-- -->
  var i;

  try {<!-- -->
    assert(i != null);
  } catch (e, s) {<!-- -->
    print("Exception: $e");
    // Output stack information
    print("Stack :$s");
  } finally {<!-- -->
    print("finally");
  }

  print("next..");
}

operation result:

2.2 on

If you don't care about the exception object, you can use on to specify what type of exception it is

main() {<!-- -->
  try {<!-- -->
    throw FormatException("too later");
  } on FormatException {<!-- -->
    print("Too late");
  }
}

operation result:

Of course, it can also be used in combination with catch:

main() {<!-- -->
  try {<!-- -->
    throw FormatException("too later");
  } on FormatException catch (e) {<!-- -->
    print("Too late");
    print(e);
  } on Exception {<!-- -->
    print("Exception");
  }
}

operation result:

3. Rethrow

rethrow can throw the exception again

main() {<!-- -->
  try {<!-- -->
    throw FormatException("too later");
  } catch (e) {<!-- -->
    print(e);
    rethrow;
  }
}

operation result:

syntaxbug.com © 2021 All Rights Reserved.