[Android Development - Dart Grammar Explanation]

Detailed explanation of Dart syntax

1. Entry method

In Dart, the entry method of a program is main()a function.

2. Dart variables

In Dart, variables can be declared using the keywords var, finaland . constAmong them, varit can be used to declare variables of any type, finaland constit can be used to declare constant variables. The difference is that constthe value of the expression has been determined at compile time, but finalcan be initialized at the time of declaration or in the constructor.

var name = "John";
final age = 30;
const PI = 3.14;

3. Dart naming rules

In Dart, identifiers must start with a letter or an underscore, and cannot start with a number; identifiers cannot contain spaces or special characters, such as @, #, $, etc.; letters in identifiers are case-sensitive. Identifiers should be named in camelCase.

int myAge = 18;
String userName = "john";

4. Dart constants

In Dart, constants can be declared using the finalor keyword. constThe difference between constants and variables is that, once initialized, the value of a constant cannot be changed; whereas the value of a variable can be modified.

final height = 1.75;
const PI = 3.14;

5. Data types

5.1 Numeric types

Numeric types in Dart include int(integer) and double(floating point).

int age = 18;
double height = 1.75;

5.1.3 Operators

Numeric types in Dart support a variety of operators, including addition, subtraction, multiplication, division, and remainder.

int a = 5;
int b = 2;
print(a + b); // 输出7
print(a - b); // 输出3
print(a * b); // 输出10
print(a / b); // 输出2.5
print(a % b); // 输出1

5.2 String type

String types in Dart are enclosed in single or double quotes.

String hello = "Hello";
String world = 'world';

5.3 Boolean type

The Boolean type in Dart has two values: trueand false.

bool isGood = true;
bool isBad = false;

5.4 List collection type

The List type in Dart can be used to store an ordered set of data, and its elements can be accessed through subscripts.

5.4.1 The first way to define List

List<String> fruits = ["apple", "banana", "orange"];

5.4.2 The second way to define List

List<int> numbers = new List();
numbers.add(1);
numbers.add(2);
numbers.add(3);

5.4.3 Specify the type of list

List<dynamic> list = new List<dynamic>();
list.add("hello");
list.add(123);
list.add(true);

5.5 Types of Maps

The Map type in Dart is used to store key-value pairs, where the key and value can be of any type.

5.5.1 The first definition method

Map<String, String> fruits = {
    
    
  "apple": "red",
  "banana": "yellow",
  "orange": "orange",
};

5.5.2 The second definition method

Map<String, int> scores = new Map();
scores["John"] = 80;
scores["Mary"] = 90;

5.6 Type judgment (is keyword)

In Dart, you can use iskeywords to determine whether an object belongs to a certain type.

String str = "Hello";
if (str is String) {
    
    
  print("str is a string");
}

6. Operators

6.2 Relational operators

The relational operators in Dart include equal to ( ==), not equal to ( !=), greater than ( ), less than ( >), greater than <or equal to ( ), >=and less than or equal to ( <=).

6.3 Logical operators

In Dart, you can use !, &&and ||three symbols to perform logical operations.

6.3.1 Reversal (!)

bool isGood = false;
if(!isGood){
    
    
  print("isBad");
}

6.3.2 And operation (&&)

bool isGood = true;
bool isBig = true;
if(isGood && isBig){
    
    
  print("isGreat");
}

6.3.3 Or operation ( | | )

bool isGood = true;
bool isBig = false;
if(isGood || isBig){
    
    
  print("isGood or isBig");
}

6.4 Assignment operation

Assignment operations in Dart include direct assignment ( =), assignment after judgment is empty ( ??=), and compound assignment operators ( +=, -=, *=, /=, %=, ~/=).

6.4.1 Direct assignment (=)

int a = 5;

6.4.2 Assign after judgment is empty (??=)

int a;
a ??= 5;
print(a); // 输出 5

6.4.3 Compound assignment operators (+=, -=, *=, /=, %=, ~/=)

int a = 5;
a += 3;
print(a); // 输出 8

6.5 Conditional expressions

In Dart, conditional expressions can be implemented using if-elsestatements, switch-casestatements, ternary operators, and ??operators.

6.5.1 if else

int score = 80;
if (score >= 90) {
    
    
  print("Grade A");
} else if (score >= 80) {
    
    
  print("Grade B");
} else {
    
    
  print("Grade C");
}

6.5.2 switch case

int score = 80;
switch (score) {
    
    
  case 90:
    print("Grade A");
    break;
  case 80:
    print("Grade B");
    break;
  default:
    print("Grade C");
}

6.5.3 Trinocular operation ( ? : )

int score = 80;
String grade = score >= 90 ? "A" : "B";
print(grade); // 输出 B

6.5.4 The ?? operator

int a;
int b = a ?? 5;
print(b); // 输出 5

6.6 Type Conversion

In Dart, you can use asand isto perform type conversion.

String str = "123";
int num1 = int.parse(str); // 字符串转整数
double num2 = double.parse(str); // 字符串转浮点数
int a = 5;
String b = a.toString(); // 数字转字符串

7. Loop statement

In Dart, you can use the for, , whileand do-whilethree loop statements to handle repetitive tasks.

7.1 for loop

for (int i = 0; i < 10; i++) {
    
    
  print(i);
}

7.2 while和do while

int i = 0;
while (i < 10) {
    
    
  print(i);
  i++;
}

int j = 0;
do {
    
    
  print(j);
  j++;
} while (j < 10);

7.3 break和continue

Within a loop, the breakand continuekeywords can be used to control the flow of the program.

for (int i = 0; i < 10; i++) {
    
    
  if (i== 5)
  {
    
     break; // 中断循环 } 
  if (i % 2 == 0) {
    
    
  continue; // 跳过本次循环,进入下一次循环 
  }
  print(i); 
  }

8. Functions

In Dart, a function is a block of code with a name and parameters that can be called repeatedly.

8.1 Defining functions

int sum(int a, int b) {
    
    
  return a + b;
}

8.2 Function parameters

Function parameters in Dart can be divided into required parameters, optional positional parameters and optional named parameters.

8.2.1 Required parameters

int sum(int a, int b) {
    
    
  return a + b;
}

sum(1, 2); // 输出 3

8.2.2 Optional positional parameters

int sum(int a, [int b = 0, int c = 0]) {
    
    
  return a + b + c;
}

sum(1); // 输出 1
sum(1, 2); // 输出 3
sum(1, 2, 3); // 输出 6

8.2.3 Optional named parameters

int sum(int a, {
    
    int b = 0, int c = 0}) {
    
    
  return a + b + c;
}

sum(1); // 输出 1
sum(1, b: 2); // 输出 3
sum(1, b: 2, c: 3); // 输出 6

8.3 Anonymous functions

In Dart, you can use anonymous functions to define a function without a name.

var sum = (int a, int b) {
    
    
  return a + b;
};

print(sum(1, 2)); // 输出 3

9. Classes and Objects

In Dart, everything is an object. Every object is an instance of a class, and all classes inherit from the Object class.

9.1 Defining classes

class Person {
    
    
  String name;
  int age;

  void sayHello() {
    
    
    print("Hello, my name is $name.");
  }
}

var person = new Person();
person.name = "Tom";
person.age = 20;
person.sayHello(); // 输出 Hello, my name is Tom.

9.2 Constructors

In Dart, a constructor is a special function used to create and initialize objects of a class.

9.2.1 Default constructor

class Person {
    
    
  String name;
  int age;
  
  Person(this.name, this.age);
  
  void sayHello() {
    
    
    print("Hello, my name is $name, I'm $age years old.");
  }
}

var person = new Person("Tom", 20);
person.sayHello(); // 输出 Hello, my name is Tom, I'm 20 years old.

9.2.2 Named constructors

class Person {
    
    
  String name;
  int age;
  
  Person(this.name, this.age);
  
  Person.fromMap(Map<String, dynamic> map) {
    
    
    name = map['name'];
    age = map['age'];
  }
  
  void sayHello() {
    
    
    print("Hello, my name is $name, I'm $age years old.");
  }
}

var person = new Person.fromMap({
    
    "name": "Tom", "age": 20});
person.sayHello(); // 输出 Hello, my name is Tom, I'm 20 years old.

9.3 Static members

In Dart, statickeywords can be used to define static members, static methods and static variables can be accessed without instantiating objects.

class Person {
    
    
  String name;
  int age;
  static String hobby = "Dancing";

  Person(this.name, this.age);
  
  static void sayHello() {
    
    
    print("Hello, I love $hobby.");
  }
}

Person.sayHello(); // 输出 Hello, I love Dancing.

10. Exception handling

In Dart, try-catchexceptions can be caught and handled using statements.

try {
    
    
  int result = 10 ~/ 0; // 抛出异常
} catch (e) {
    
    
  print("Exception: $e"); // 输出 Exception: IntegerDivisionByZeroException
} finally {
    
    
  print("Finally block."); // 输出 Finally block.
}

11. File Operation

In Dart, you can use dart:iolibraries for file operations.

11.1 Reading files

import 'dart:io';

void main() async {
    
    
  var file = File('example.txt');
  var contents = await file.readAsString();
  print(contents);
}

11.2 Writing to a file

import 'dart:io';

void main() async {
    
    
  var contents = 'Hello, world!';
  var file = File('example.txt');
  await file.writeAsString(contents);
}

Guess you like

Origin blog.csdn.net/muzillll/article/details/131223949