返回
Dart语言基础语法,助力Flutter开发!
前端
2024-02-13 00:20:06
Dart基础语法概述
Dart语言是一种面向对象、编译型编程语言,语法简洁易学,代码风格与Java、C++等语言相似。Dart语言支持类型系统、类、继承、泛型等特性。Dart语言主要用于开发移动应用程序和Web应用程序。
Dart变量类型
Dart变量类型包括基本类型和引用类型。基本类型包括数字、字符串、布尔值、null。引用类型包括函数、类和对象。变量的类型可以显式声明,也可以隐式声明。
// 基本类型
int age = 18;
double weight = 75.5;
String name = "John Doe";
bool isAlive = true;
// 引用类型
Function greet = () => print("Hello, world!");
class Person {
String name;
int age;
Person(this.name, this.age);
}
Dart控制流
Dart语言支持if语句、switch语句、for循环、while循环、do-while循环等控制流语句。
// if语句
if (age >= 18) {
print("You are an adult.");
} else {
print("You are a child.");
}
// switch语句
switch (name) {
case "John":
print("Hello, John!");
break;
case "Jane":
print("Hello, Jane!");
break;
default:
print("Hello, stranger!");
}
// for循环
for (var i = 0; i < 10; i++) {
print(i);
}
// while循环
while (age < 18) {
print("You are still a child.");
age++;
}
// do-while循环
do {
print("You are still a child.");
age++;
} while (age < 18);
Dart函数
Dart语言支持函数,函数可以被其他函数调用。函数可以带参数,也可以不带参数。函数的返回值类型可以是void、基本类型或引用类型。
// 带参数的函数
void greet(String name) {
print("Hello, $name!");
}
// 不带参数的函数
int getAge() {
return 18;
}
// 主函数
void main() {
greet("John");
print(getAge());
}
Dart类和对象
Dart语言支持类和对象,类是对象的模板,对象是类的实例。类可以包含属性和方法。属性是对象的变量,方法是对象的函数。
// 定义类
class Person {
String name;
int age;
// 构造函数
Person(this.name, this.age);
// 方法
void greet() {
print("Hello, my name is $name and I am $age years old.");
}
}
// 创建对象
Person john = Person("John", 18);
// 调用方法
john.greet();
Dart泛型
Dart语言支持泛型,泛型可以使代码更灵活、更可重用。泛型可以定义为类型参数,类型参数可以是任何类型。
// 定义泛型类
class List<T> {
List() {
// ...
}
void add(T value) {
// ...
}
T removeAt(int index) {
// ...
}
}
// 使用泛型类
List<String> names = List<String>();
names.add("John");
names.add("Jane");
String name = names.removeAt(0);
结语
本文介绍了Dart语言的基础语法,包括变量类型、控制流、函数、类和对象、泛型等。掌握Dart语言的基础语法,可以帮助您快速上手Flutter开发。希望本文对您有所帮助。