• Dart Syntax basics for Flutter development
  • DartIs a programming language launched by Google in 2011. It is structuredWebProgramming language that allows users to passChromiumVirtual machines (Dart VM) Direct operationDartLanguage written procedures, the need to separate the steps of compilation
  • In the future these programs will start fromDart VMBenefits from faster performance with lower startup latency
  • DartFrom the beginning of the design to match the modernwebIn terms of overall performance, the development team is also constantly improvingDarttoJavaScriptFast compiler for transformations
  • Dart VMAs well as the modernJavaScriptThe engines (V8, etc.) are bothDartThe preferred target platform for the language
  • DartLanguage andSwiftThere are many similarities between languages

Important concepts

Before you learn the Dart language, learn some Dart concepts:

  • inO-ObjectiveThere is the saying that everything is an object in theDartThe same applies to
    • Everything that can be referenced using variables is an object, and each object is an instance of a class
    • inDartEven numbers, methods andnullAre all objects
    • All objects inherit fromObjectclass
  • DartDynamically typed languages, which try to define a type for a variable, are safer, and do not display the type of the variable indebugIn mode, the type will bedynamic(dynamic)
  • DartParses all of your code before it runs, specifying data types and compile-time constants to speed things up
  • DartClass is an interface, you can inherit a class, you can implement a class (interface), naturally also contains good object-oriented and concurrent programming support
  • Dartfunction
    • Support for top-level functions (e.gmain())
    • Support for defining functions in classes, such as static and instance functions
    • You can also define methods (nested or local) within methods
  • Similarly,DartSupport for top-level variables, as well as class – or object-dependent (static and instance) variables. Instance variables are sometimes referred to as fields or properties
  • DartThe keyword is not availablepublic.protectedandprivate. If an identifier is underlined(_)To begin with, both it and its libraries are private
  • Identifiers can start with a letter or (_), or with a combination of characters and numbers

The above Outlines some of the key concepts in Dart. See below for syntax usage

The basic grammar

annotation

Dart comments come in three types: single-line comments, multi-line comments, and document comments

  • A single line comment//At the beginning
  • Multi-line comments to/ *At the beginning,* /At the end
  • Document comments with///or/ * *At the beginning

A semicolon.

  • A semicolon is used for separationDartstatements
  • Usually we add a semicolon to the end of each executable statement
  • Another use for semicolons is to write multiple statements in a single line
  • inDartIt is necessary to end a statement with a semicolon, otherwise an error will be reported

Other grammar

  • In accordance with theDartThe programming specification uses two Spaces for indentation
  • Output statement usingprint(Object)

Variables and constants

variable

Declare variables using the var, Object, or dynamic keywords

var name = 'name';
dynamic name1 = 'name1';
String name2 = 'name2';

// Variable assignment
name = 'a';
name1 = 'a1';
name2 = 'a2';
Copy the code

Uninitialized variables have an initial value of NULL, even for numbers, because numbers are also objects in Dart

var name;
dynamic name1;
String name2;
Copy the code

Optional type

When declaring a variable, you can optionally add a specific type:

String name2 = 'name2';
Copy the code
  • This way you can more clearly express the type of variable you want to define, and the compiler can provide you with code completion and bug detection based on that type
  • Note: For local variables, this followsCode Style RecommendationsPart of the recommendations for usevarLocal variables are defined not by specific types

constant

  • Constant usefinalorconst
  • afinalA variable can only be assigned once
  • aconstVariables are compile-time constants
  • The instance variable can befinalBut it can’t beconst

final

Final modified variable (constant 2)

  final age = 10;
  final int age1 = 20;

  // Final variables cannot be reassigned and an error is reported
  age = 20;
  age1 = 30;
Copy the code

const

  • constVariables are compile-time constants
  • If used in a classconstTo define a constant, define asstatic const
  • useconstA defined constant, which can be given an initial value directly or can be used elsewhereconstThe value of a variable to initialize its value
  // const
  const m1 = 12;
  const double m2 = 23;
  const m3 = m1 + m2;

  // Final variables cannot be reassigned and an error is reported
  m1 = 10;
  m2 = 1.02;
Copy the code

The operator

Arithmetic operator

Dart supports common arithmetic operators

The operator explain
+ A plus sign
- A minus sign
-expr Minus sign
* Multiplication sign
/ The divisor (value isdoubleType)
~ / Divisor, but returns an integer
% modulus

Example:

assert(2 + 3= =5);
assert(2 - 3= =- 1);
assert(2 * 3= =6);
assert(5 / 2= =2.5);   // The result is of type double
assert(5~ /2= =2);    // The result is of type INTEGER
assert(5 % 2= =1);     / / remainder
Copy the code

Since the decrement

Dart also supports add and subtract operations

  • ++var: Self add before use
  • var++: used first in self-add
  • --var: Reduce in use first
  • var--: Used first in autosubtract

The sample

  var a = 0, b = 0;
  
  b = a++;
  print('a = $a, b = $b'); //a = 1, b = 0
  b = ++a;
  print('a = $a, b = $b'); //a = 2, b = 2


  b = a--;
  print('a = $a, b = $b'); //a = 1, b = 2
  b = --a;
  print('a = $a, b = $b'); //a = 0, b = 0
Copy the code

Relational operator

The operator meaning
= = Is equal to the
! = Is not equal to
> Is greater than
< Less than
> = Greater than or equal to
< = Less than or equal to
  • To test whether two objects represent the same thing, use the= =The operator
  • In some cases, you need to know if two objects are the same object, usingidentical()methods
external bool identical(Object a, Object b);
Copy the code

Type determination operator

Type determination operators are operators that determine the type of an object at run time

The operator explain
as Type conversion
is Returns True if the object is of the specified type
is! Returns False if the object is of the specified type
  • Only when theobjTo achieve theTThe interface,obj is TIs thetrue. For example,obj is Objectalwaystrue
  • useasThe operator converts an object to a specific type
  • Can put theasIt for useisDetermine the type and then call the abbreviation of the function that determines the object
if (emp is Person) { // Type check
  emp.firstName = 'Bob';
}

// The above code can be simplified as
(emp as Person).firstName = 'Bob';
Copy the code

Note: If emP is null or not of type Person, the first example uses IS and does not execute the code in the condition, while the second case uses AS and raises an exception. Therefore, in the case that there is no shortage of emP is empty, the first method is recommended to be safe

The assignment operator

= - = / = % = > > = ^ =
+ = * = ~ / = < < = & =

Example:

// Assign a value to variable A
a = value;  

// The compound assignment operator
a += b;  // a = a + b;

// If b is null, assign to b;
// If not null, the value of b remains unchangedb ?? = value;// As shown below:
  var s;
  print(s);  // null
  print(s ?? 'str');  // strs ?? ='string';
  print(s);  // string
Copy the code

Logical operator

Boolean values can be manipulated using logical operators:

  • ! expr: negates the result of the expression (true to false, false to true)
  • ||: logical OR
  • &&Logic AND:

Conditional expression

condition ? Expr1: expr2 // if condition istrue, executes exPR1 (and returns the result of execution); Otherwise, execute expr2 and return the result expr1?? Expr2 // If expr1 is non-null, return its value; Otherwise, exPR2 is executed and the result is returnedCopy the code

Example:

String toString() => msg ?? super.toString(); String toString() => MSG == null? super.toString() : msg; // Equivalent to StringtoString() {
  if (msg == null) {
    return super.toString();
  } else {
    returnmsg; }}Copy the code

Cascade operators

Cascade operators (..) Multiple functions can be called consecutively on the same object and member variables can be accessed. Using cascade operators avoids creating temporary variables, and the written code looks smoother

querySelector('#button') // Get an object.
  ..text = 'Confirm'   // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed! '));
Copy the code

The first method querySelector() returns a selector object. The subsequent cascade operators are members that call this object and ignore the value returned by each operation

// The above code is equivalent to
var button = querySelector('#button');
button.text = 'Confirm';
button.classes.add('important');
button.onClick.listen((e) => window.alert('Confirmed! '));
Copy the code

Cascading calls can also be nested:

final addressBook = (newAddressBookBuilder() .. name ='jenny'
      ..email = '[email protected]'
      ..phone = (newPhoneNumberBuilder() .. number ='415-555-0100'
            ..label = 'home')
          .build())
    .build();
Copy the code

Note: Strictly speaking, the two-point concatenation is not an operator, just a Dart special syntax.

Flow control statement

Dart allows you to control the flow of Dart code with the following statements:

  • if-else
  • forandfor-in
  • whileanddo-while
  • switch
  • assert
  • breakandcontinue
  • try-catchandthrow

if-else

Dart supports the if statement and optional ELSE

  if (a == 0) {
    print('a = 0');
  } else if (a == 1) {
    print('a = 1');
  } else {
    print('a = 2');
  }
Copy the code

Note: The result of the conditional control statement in the above code must be a Boolean value

for

You can use the standard for loop. Classes such as List and Set that implement the Iterable interface also support for-in traversal:

  var arr = [0.1.2];

  / / a for loop
  for (var i = 0; i < arr.length; i++) {
    print(arr[i]);
  }
  
  / / the for - in circulation
  for (var x in arr) {
    print(x);
  }
Copy the code

Whileanddo-while

  // While determines whether the condition is met before executing the loop:
  while (c == 0) {
    print('c = $c');
  }

  // The do-while loop executes the code before judging the condition:
  do {
    print('c = $c');
  } while (c == 0);
Copy the code

Breakandcontinue

Use break to terminate the loop:

while (true) {
  if (shutDownRequested()) break;
  processIncomingRequests();
}
Copy the code

Use continue to start the next loop

for (int i = 0; i < candidates.length; i++) {
  var candidate = candidates[i];
  if (candidate.yearsExperience < 5) {
    continue;
  }
  candidate.interview();
}
Copy the code

Switch

  • DartIn theSwitchStatements use= =To compareinteger,stringOr compile-time constants
  • The objects to be compared must all be instances of the same class, suitable for enumeration values
  • Each non-emptycaseStatements must have onebreakstatements
  • You can also go throughcontinue,throworreturnTo end non-emptycasestatements
  • When there is nocaseThis parameter can be used when the statement matchesdefaultStatement to match the default
  • eachcaseStatements can have local variables that are visible only within the statement
  var command = 'OPEN';
  switch (command) {
    case 'CLOSED':
      print('CLOSED');
      break;
    case 'APPROVED':
      print('APPROVED');
      // break;
      // this is not an empty case
    case 'DENIED':
      // empty case, can not break
    case 'OPEN':
      print('OPEN');
      continue nowClosed;
  // If you want to proceed to the next case statement, you can use the continue statement to jump to the corresponding label and continue execution:
  nowClosed:
    case 'PENDING':
      print('PENDING');
      break;
    default:
      print('default');
  }
Copy the code

Assert

  • Assertion: Can be used if the result of a conditional expression is not satisfactoryassertStatement interrupts the execution of code
  • assertThe argument to a method can be any expression or method that returns a Boolean.
  • If the value returned istrue, the assertion execution passes, and the execution ends
  • If the return value isfalseIf the assertion fails, an exception will be thrown
  • It can be used during development to monitor code for problems
// Make sure the variable has a non-null value
assert(text ! =null);

// Make sure the value is less than 100
assert(number < 100);

// Make sure this is an https URL
assert(urlString.startsWith('https'));
Copy the code

Note: Assertions are only valid when run in development mode; if run in production mode, they are not executed

That concludes the brief introduction to this article, and the next article will document the basic data types for Dart

reference

  • Dart official website syntax introduction – Chinese version
  • Dart official website syntax introduction – English version

Please scan the following wechat official account and subscribe to my blog!