Introduction to the

Dart ([KK] ɑrt/, [DJ] ɑ:t/)

Dart is an open source programming language for the World Wide Web. It was developed by Google and made public in October 2011. Its development team, led by Lars Barker, who led the V8 team for Google Chrome, aims to become the next generation of structured Web development language. Like JavaScript, Dart is an object-oriented language, but it uses class-based programming. It allows only single inheritance and has a syntactic style close to C. — Wikipedia

Without further ado, here’s what Dart looks like:

// Define a function.
printInteger(int aNumber) {
  print('The number is $aNumber.'); // Print to console using string interpolation.
}

// This is where the application starts execution.
main() {
  var number = 42; // Declare and initialize variables.
  printInteger(number); // Call a function.
}
Copy the code

Dart functions must be declared before they are called, with the declaration code written before the calling code.

Dart variable type

1. Use var to declare a variable and assign a value (official recommendation) :

var name = 'Bob' ; 
Copy the code

Variables store references. The variable name contains a reference to an object whose String value is “Bob”. Name infers the variable’s type String, but it can also be changed by specifying it.

2. If the object is not limited to a single type, we can also use dynamic:

dynamic name = 'Bob' ;
Copy the code

3. Another option is to explicitly declare the types that can be inferred:

String name = 'Bob' ; 
Copy the code

Note: If only variables are declared and no values are assigned, the default value is NULL, including numeric variables. Everything is an object in Dart, and numbers are an object type, such as:

num lineCount;  
lineCount ==null;// true  
Copy the code

The final and const

If you do not intend to change a variable, use a final or const declaration. Both filal and const variables can be assigned only once at initialization and cannot be changed after declaration. Const variables are compile-time constants.

Note: Instance variables can be final, but not const.

Here is an example of creating and setting the final variable:

final name = 'Bob' ; // No type comment
final String nickname = 'Bobby' ;  
Copy the code

Cannot change the value of the final variable:

name = 'Alice' ; // Error: The final variable can only be set once.
Copy the code

Dart Built-in types

The Dart language specifically supports the following types:

  • numbers
  • strings
  • booleans
  • Lists (also called arrays)
  • maps
  • Runes (used to represent Unicode characters in strings)
  • symbols

Because each variable in Dart refers to an object, an instance of a class, you can usually use constructors to initialize variables. Some built-in types have their own constructors. For example, you can use the Map() constructor to create a Map object.

There are two types of Numbers

Int: Integer value not larger than 64 bits, depending on platform.

Double: 64-bit (double precision) floating point number.

Int and double are subtypes of number.

String and numeric type interconversion:

// String -> int
var one = int.parse('1');
assert(one == 1);

// String -> double
var onePointOne = double.parse('1.1');
assert(onePointOne == 1.1);

// int -> String
String oneAsString = 1.toString();
assert(oneAsString == '1');

// double -> String
String piAsString = 3.14159.toStringAsFixed(2);
assert(piAsString == '3.14');
Copy the code

2. Strings

Strings can be created using either single quotes “” or double quotes” “:

var s1 = 'Single quotes work well for string literals.';
var s2 = "Double quotes work just as well.";
Copy the code

An expression can be put into a string with ${expression}. If expression is an identifier, the curly braces {} can be omitted. Dart calls the object’s toString () method to get the string corresponding to the object.

Strings can be concatenated using adjacent string literals or the + operator:

var s1 = 'String ''concatenation'" works even over line breaks.";
assert(s1 == 'String concatenation works even over ''line breaks.'); 

var s2 = 'The + operator ' + 'works, as well.';
assert(s2 == 'The + operator works, as well.'); 
Copy the code

Another way to create a multi-line string is to use triple quotes with single or double quotes:

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

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

The “raw” string r can be created by prefixing it:

var s = r'In a raw string, not even \n gets special treatment.';
Copy the code

3. Booleans

Boolean values are declared as bool. The values are true and false, which are compile-time constants.

// Check for an empty string.
var fullName = ' ';
assert(fullName.isEmpty);

// Check for zero.
var hitPoints = 0;
assert(hitPoints <= 0);

// Check for null.
var unicorn;
assert(unicorn == null);

// Check for NaN.
var iMeantToDoThis = 0 / 0;
assert(iMeantToDoThis.isNaN);
Copy the code

4. Lists

Dart lists are similar to JavaScript lists. Here’s how they are declared:

var list = [1.2.3];
Copy the code

Note: The parser deduces that list has type list. If you try to add a non-integer object to this list, the parser or runtime raises an error.

List index usage starts at 0, where 0 is the index of the first element and list.length-1 is the index of the last element.

5. Maps

Typically, a map is an object associated with a key and value. Keys and values can be objects of any type. Each key appears only once, but the same value can be used multiple times.

Example declaration:

var gifts = {
  // Key: Value
  'first': 'partridge'.'second': 'turtledoves'.'fifth': 'golden rings'
};

var nobleGases = {
  2: 'helium'.10: 'neon'.18: 'argon'};Copy the code

The gifts element type Map

and the nobleGases element type Map

. If you try to add a value of the wrong type to any map, the parser or runtime raises an error.
,>
,>

You can also create the same object using the Map constructor:

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

var nobleGases = Map(a); nobleGases[2] = 'helium';
nobleGases[10] = 'neon';
nobleGases[18] = 'argon';
Copy the code

Note: You might want to see new Map() instead of just Map(). Starting with Dart 2, the new keyword is optional.

var gifts = {'first': 'partridge'};

/ / to add
gifts['fourth'] = 'calling birds'; // Add a key-value pair

/ / delete
gifts.remove('first');

/ / change
gifts['fourth'] = '1234'; 

/ / check
var item = gifts['fourth'];
Copy the code

6. Functions

Dart is a true object-oriented language, so even functions are objects and have a Function type. This means that functions can be assigned to variables or passed as arguments to other functions. You can also call an instance of the Dart class as if it were a function.

Function examples:

bool isNoble(int atomicNumber) {
  return_nobleGases[atomicNumber] ! =null;
}

// You can omit the return value type
isNoble(atomicNumber) {
  return_nobleGases[atomicNumber] ! =null;
}

// Arrow function
bool isNoble(intatomicNumber) => _nobleGases[atomicNumber] ! =null;

Copy the code

Important concepts

Keep the following facts and concepts in mind as you learn about the Dart language:

  • Everything you can put in a variable is an object, and each object is an instance of a class. Even numbers, functions and null objects. All objects inherit from the Object class.

  • Although Dart is strongly typed, type annotations are optional because Dart can infer types. In the above code, number is inferred to be of type int. To specify that no type is required, use the special type Dynamic.

  • Dart supports generic types such as List (a List of integers) or List (a List of objects of any type).

  • Dart supports top-level functions (such as main()), as well as functions bound to classes or objects (static and instance methods, respectively). You can also create functions (nested or local) within functions.

  • Similarly, Dart supports top-level variables, as well as variables (static and instance variables) bound to classes or objects. Instance variables are sometimes called fields or properties.

  • Like Java, Dart does not have the keywords public, protected, and private. If an identifier begins with an underscore (_), it is private to its library.

  • Identifiers can begin with a letter or underscore (_), followed by any combination of these characters plus numbers.

  • Sometimes it is important whether something is expressive or declarative, so it helps to understand the two words accurately.

  • The Dart tool can report two types of problems: warnings and errors. Warnings simply indicate that your code may not work properly, but they do not prevent your program from executing. The error can be compile-time or run-time. Compile-time errors prevent code execution; Runtime errors cause code execution to throw exceptions.

Epilogue: This article is a note made by myself during Dart learning. In this way, the knowledge framework is relatively complete and easy to review repeatedly, as well as convenient for other partners to check. Almost all of the content in this article comes from Dart Programming language, and some of it comes from the Internet. If there is any similarity, I copied it completely. Ha ha ~