[Dart language decryption] Want to learn more about Dart syntax and type variables?

Come and read this article! From the perspective of Dart information representation, this article explains in detail the basic syntax and type variables of Dart. Through the study of this article, you will have a deeper knowledge and understanding of the Dart language, and better master the development skills and practical applications of Dart. Come and decrypt the Dart language together!

1 Dart hello world example

Create a new main.dart, declare a function with an int parameter, and print this parameter through a string embedded expression:

printInteger(int a) {
    
    
  print('Hello world, this is $a.');
}

main() {
    
    
  var number = 2019;
  printInteger(number);
}

output:

Hello world, this is 2019.

Dart also requires main to be the execution entry point.

2 Dart variables and types

A variable can be declared with var or a concrete type:

  • When using var to define a variable, the type is deduced by the compiler
  • Static types can also be used to define variables, expressing intent more clearly with the compiler, so that editors and compilers can use these static types to provide you with code completion or compilation warning prompts

By default, the values ​​of uninitialized variables are all null, so don't worry about writing a bunch of judgment statements because you can't determine whether a passed undefined variable is undefined or hot.

Dart is a type-safe language, and all types are object types, which inherit from the top-level type Object, so all variable values ​​​​are instances of classes (that is, objects), and numbers, boolean values, functions and null are also inherited from Object Object.

Dart has built-in basic types, such as num, bool, String, List, and Map, which can be used to declare variables without introducing other libraries.

2.1 num, bool and String

As the most commonly used types in programming languages, I introduced the three basic types of num, bool, and String together.

Dart's numeric type num has only two subtypes : 64-bit int and 64-bit double that conform to the IEEE 754 standard. The former represents integer types, while the latter is an abstraction for floating-point numbers. Under normal circumstances, their precision and value range are sufficient to meet our demands.

int x = 1;
int hex = 0xEEADBEEF;
double y = 1.1;
double exponents = 1.13e5;
int roundY = y.round();

In addition to common basic operators, such as +, -, *, /, and bitwise operators, you can also use abs(), round() and other methods inherited from num to realize the functions of absolute value and rounding .

Open the official documentation or view the source code, these common operators are also inherited from num:

Figure 1: Operators in num

If num cannot meet the needs of other advanced calculation methods, you can try the dart:math library, which provides advanced functions such as trigonometric functions, exponents, logarithms, and square roots.

To represent Boolean values, Dart uses a type called bool. Dart has only two objects of type bool: true and false, both compile-time constants.

Dart is type-safe, you cannot use if(nonbooleanValue) or assert(nonbooleanValue) code that works normally in js, but check the value explicitly.

As follows, check whether the variable is 0, which needs to be compared with 0 explicitly in Dart:

// 检查是否为0.
var number = 0;
assert(number == 0);
// assert(number); 错误

Dart's String consists of UTF-16 strings. Like JavaScript, you can use either single quotes or double quotes when constructing string literals, and you can embed variables or expressions in strings: you can use ${express} to put the value of an expression into a string . And if it's an identifier, you can omit {}.

Examples of inline expressions. Capitalize the word 'cat' into the declaration of variable s1:

var s = 'cat';
var s1 = 'this is a uppercased string: ${
      
      s.toUpperCase()}';

To get the string of an embedded object, Dart calls the object's toString() method. For the concatenation of common strings, Dart implements it through the built-in operator "+". For example, the following statement declares a string whose value is 'Hello World!' as you would expect:

var s2 = 'Hello' + ' ' + 'World!' ;

For the construction of multi-line strings, you can declare with three single quotes or three double quotes, which is consistent with Python:

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

2.2 List and Map

Common array and dictionary types in other programming languages, the corresponding implementations in Dart are List and Map, collectively referred to as collection types. Their declaration and use are simple, similar to usage in JavaScript.

Next, let's look at a code example together.

  • In the first half of the code example, we declare and initialize two List variables. After adding a new element to the second variable, call its iteration method to print out its internal elements in turn;
  • In the second half of the code example, we declare and initialize two Map variables. After adding two key-value pairs to the second variable, we also call its iteration method to print out its internal elements in sequence.
var arr1 = ["Tom", "Andy", "Jack"];
var arr2 = List.of([1,2,3]);
arr2.add(499);
arr2.forEach((v) => print('${
      
      v}'));

var map1 = {
    
    "name": "Tom", 'sex': 'male'};
var map2 = new Map();
map2['name'] = 'Tom';
map2['sex'] = 'male';
map2.forEach((k,v) => print('${
      
      k}: ${
      
      v}'));

The elements in the container also need to have types. For example, the type of arr2 in the above code is List , and the type of map2 is Map<String, String> . Dart will automatically perform type inference based on the context, so the elements you add to the container must also follow this type.

If the type automatically inferred by the compiler does not meet expectations, we can of course mark the type explicitly when declaring, not only to make the code hints more friendly, but more importantly, to allow the static analyzer to help check for errors in literals , to remove security risks or bugs caused by type mismatch.

Take the above code as an example, if a floating point number arr2.add(1.1) is added to the arr2 collection , although it is semantically legal, the compiler will prompt that the types do not match, resulting in compilation failure.

Similar to the Java language, when you initialize a collection instance object, you can add constraints to its type, which can also be used to determine the collection type later.

In the following code, after adding type constraints, is the semantics clearer?

var arr1 = <String>['Tom', 'Andy', 'Jack'];
var arr2 = new List<int>.of([1,2,3]);
arr2.add(499);
arr2.forEach((v) => print('${
      
      v}'));
print(arr2 is List<int>); // true

var map1 = <String, String>{
    
    'name': 'Tom','sex': 'male',};
var map2 = new Map<String, String>();
map2['name'] = 'Tom';
map2['sex'] = 'male';
map2.forEach((k,v) => print('${
      
      k}: ${
      
      v}'));
print(map2 is Map<String, String>); // true

2.3 Constant definition

If you want to define an immutable variable, you need to add the final or const keyword before the variable definition:

  • const, indicating the value of the variable that can be determined during compilation;
  • Final is not the same, the variable defined with it can determine the value at runtime, but once determined, it cannot be changed.

A typical example of declaring const constants and final constants is as follows:

final name = 'Andy';
const count = 3;

var x = 70;
var y = 30;
final z = x / y;

It can be seen that const is suitable for defining compilation constants (literal fixed values), while final is suitable for defining runtime constants.

3 summary

Through the above introduction, I believe you have a preliminary impression of Dart's basic syntax and type system. These initial impressions will help you understand the basic ideas of Dart language design, and get started quickly on the basis of existing programming language experience.

As for flow control syntax: such as if-else, for , while , do-while , break/continue, switch-case, assert , since it is similar to other programming languages, I will not introduce them one by one here, and more Dart language features require you to learn slowly in the subsequent use process. Using the Dart process, the official documentation is the most important learning material.

  • In Dart, all types are object types and inherit from the top-level type Object, so all variables are objects, including numbers, Boolean values, functions and null;
  • The values ​​of uninitialized variables are all null;
  • Specify types for variables so that both the editor and the compiler can better understand your intent.

4 FAQ

For the collection types List and Map, how to make its internal elements support multiple types (for example, int, double)? And how to judge what type it is when traversing the collection?

In the Dart language, List and Map support storing elements of various types. The type of the internal elements of the collection can be specified through generics. like:

List<dynamic> myList = [1, 2.0, 'three'];
Map<String, dynamic> myMap = {
    
    'name': 'Alice', 'age': 30, 'height': 1.65};

The element types of List and Map are dynamic, which means that any type of element can be stored.

To determine the element type when traversing a collection, use the type checking operator is in Dart. like:

// 使用is运算符判断了每个元素的类型,并打印了相应信息。
List<dynamic> myList = [1, 2.0, 'three'];
for (var element in myList) {
    
    
  if (element is int) {
    
    
    print('$element is an integer');
  } else if (element is double) {
    
    
    print('$element is a double');
  } else if (element is String) {
    
    
    print('$element is a string');
  }
}

Guess you like

Origin blog.csdn.net/qq_33589510/article/details/131344352