Dart 语言基础
Dart 是 Flutter 的语言基础。语法混合了 Java(类型)和 JS(函数式)的特点,上手不难。
基础语法
var 类型推断;final 常量(运行期确定);const 编译期常量。类型:int、double、String、bool、List、Map。
函数
命名参数 {required}、可选参数 []、箭头函数、闭包。
面向对象
class、构造函数、this、继承、接口(implements)、混入(mixin)。async/await 异步。
代码示例
void main() {
// 变量
var name = "张三";
final int age = 25; // 运行期常量
const city = "烟台"; // 编译期常量
// 集合
List<String> tags = ["前端", "Flutter"];
Map<String, int> scores = {"语文": 90, "数学": 95};
// 函数
int add(int a, int b) => a + b;
// 命名参数函数
void greet({required String name, String msg = "你好"}) {
print("$msg, $name!");
}
// 异步
Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 1));
return "数据";
}
greet(name: name);
fetchData().then((d) => print(d));
}