一、声明
变量声明
在程序执行期间可以具有不同的值。
var name = 'Peter'; String name = 'William'; name = 'Eason';延迟初始化变量。
late String name; // 变量延时赋值 late String temperature = readThermometer(); // 变量被使用时,函数才会调用常量声明
编译时确定的常量。
const age = 27; const int age = 27; const name = 'Peter'; const String name = 'Peter';运行时确定的常量。
final timestamp = DateTime.now().toString(); final String timestamp = DateTime.now().toString(); final score = calculateScore(); final double score = calculateScore();二、类型
num类型
num 类型覆盖了任何整数和浮点数。
// 整形 var count = 1; int age = 12; num length = 50; // 浮点数 var score = 87.5; double price = 29.99; num width = 375.0; // string -> int int count = int.parse('1'); // 1 // string -> double double price = double.parse('29.99'); // 29.99 // int -> string String countStr = 1.toString(); // '1' // double -> string String priceStr = 29.99.toStringAsFixed(2); // '29.99'bool类型
bool 由 true 和 false 两个逻辑值组成。
bool isEmpty = ''.isEmpty; bool isZero = (int.parse('1') == 0);String类型
String 字符串类型。
String name = 'Peter'; String content1 = 'He's name is ${name}.'; String content2 = 'He's name is' + name + '.';List类型
var list1 = const ['Car', 'Boat', 'Plane']; List<String> list2 = []; // 不支持 List<String>() 构造 List<String> fruits = ['apple', 'orange']; fruits.add('banana'); // ['apple', 'orange', 'banana'] fruits.addAll(['pear']); // ['apple', 'orange', 'banana', 'pear'] fruits.remove('orange'); // ['apple', 'banana', 'pear'] fruits.removeAt(0); // ['banana', 'pear'] fruits.insert(1, 'orange'); // ['banana', 'orange', 'pear'] int idx = fruits.indexOf('orange'); // 1 bool isContains = fruits.contains('apple'); // false fruits.clear(); // []Set类型
var halogens = {'fluorine', 'chlorine', 'bromine', 'iodine', 'astatine'}; var names = Set<String>(); Set<String> fruits = {'apple', 'orange'}; fruits.add('banana'); // {'apple', 'orange', 'banana'} fruits.addAll({'pear'}); // {'apple', 'orange', 'banana', 'pear'} fruits.remove('apple'); // {'orange', 'banana', 'pear'} fruits.clear(); // {}Map类型
Map 类型,存储 key-value 键值对。
var names = const {'first': 'Peter', 'second': 'Lucy', 'third': 'Eason'}; var gifts = Map<String, String>(); Map<int, String> fruits = {1: 'apple', 2: 'orange'}; fruits[3] = 'banana'; // {1: 'apple', 2: 'orange', 3: 'banana'} fruits.remove(1); // {2: 'orange', 3: 'banana'} fruits.clear(); // {}Object类型
Object 是 Dart 类型系统的根类,用于定义任意类型。
Map<String, Object> person = { 'name': 'Eason', 'age': 25 }; final String name = person["name"] as String; // as 强转(不安全) print("name: " + name); final name = person["name"]; if (name is String) { // is 判断(安全) print("name: " + name); }dynamic类型
dynamic 是 Dart 里的动态类型,编译时不做类型检查,运行时才确定具体类型,常用于 JSON 解析和原生平台通讯。
// JSON 解析 import 'dart:convert'; final dynamic json = jsonDecode('{"name": "Eason","age": 25}'); print(json["name"]); // 原生平台通讯 final dynamic result = await t_methodChannel.invokeMethod('getDeviceInfo');void类型
void 用于指定函数没有返回值。
void getDeviceId() { // do somethind }enum类型
enum 枚举用于声明一组相关值的通用类型。
// 声明 enum Direction { left, right, top, bottom } // 应用 const direction = Direction.left;// 增强型枚举 enum Direction { left(1001), right(1002), top(1003), bottom(1004); final int value; const Direction(this.value); } const value = Direction.left.value;T泛型
泛型 = 类型参数化,把“具体类型”变成“参数”,让同一份代码能安全地作用于多种类型。
// 泛型类 class Box<T> { final T value; Box(this.value); } final box = Box<int>(1); // 泛型方法 T fetchData<T>(List<T> datas) { return datas.first; } final data = fetchData<String>(["1", "2", "3"]); // 泛型接口 abstract class Cache<T> { void setValue(String key, T value); T? getValue(String key); } class DataCache<T> implements Cache<T> { final Map<String, T> map = {}; @override void setValue(String key, T value) => map[key] = value; @override T? getValue(String key) => map[key]; } final cache = DataCache<String>(); cache.setValue("key", "value"); final value = cache.getValue("key");三、语句
if语句
if (condition) { // do something }switch语句
switch (type) { case 0: // do something case 1 || 2: // 命中1或2 // do something default: // do something }for语句
for (var i = 0; i < 5; i++) { if (i == 1) { continue; } // do something } for (final name in names) { if (name == 'Peter') { break; } // do something }while语句
while (isContinue) { // do something } do { // do something } while (isContinue);try-catch语句
try { // do something } catch (e) { print('Error: $e'); } finally { }Assert语句
// 断言 - 开发环境 assert(text != null);四、操作符
三元运算符
final String str = value ? value : ''; final String str1 = value ?? '';可选链运算符
1)变量/属性的定义
int? number = null; String value = number?.toString();2)方法传参
String execute(String str1, String? str2) { return str1 + (str2 ?? ''); } execute('a', null);五、函数
函数声明/调用
必选位置参数的函数声明。
void execute(String arg1, String? arg2) { // do something } execute('title', null);bool plus(int a, int b) { return a + b; } bool plus(int a, int b) => a + b; // 方法简写可选位置参数的函数声明。
bool execute([int? number, String name = 'Peter']) { return (number?.toString == '7'); } execute(); execute(7); execute(7, 'Eason');// 必选位置 + 可选位置 bool execute(int? number, [String? name]) { return (number?.toString == '7'); } execute(7); execute(7, 'Peter');可选命名参数的函数声明。
bool execute({int? number, required String name, double? weight}) { return (number?.toString == '7'); } execute(name: 'Peter'); execute(name: 'Peter', weight: 125.5); execute(number: 7, name: 'Peter', weight: 125.5);// 必选位置 + 可选命名 bool execute(int? number, {required String name, double? weight}) { return (number?.toString == '7'); } execute(7, name: 'Peter'); execute(7, name: 'Peter', weight: 125.5);函数类型
typedef CallbackFunc = int Function(String message); void execute(CallbackFunc callback) { int code = callBack('success'); print('code: ${code}'); } int callback(String message) { print('message: ${message}'); retrun 0; } execute(callback);async/await
async/await 可以让异步逻辑同步执行,不会造成同步阻塞。async 用于申明一个 function 是异步的,返回的是一个 Future 对象,await 用于等待一个异步方法执行完成。
import 'dart:async'; Future<String> checkVersion() async { var version = await lookUpVersion(); return version; } this.checkVersion().then((String version) { print('version: $version'); }).catchError((e) { print('exception: $e'); });六、类
类声明
引入一个新类型,并定义其字段、方法和构造函数。
class Car { final String name; final String model; String style = ''; double? price; Car(String name, String model) : name = name, model = model; void execute() { print('${this.name} ${this.model}'); } }构造函数
1)不带参数
Car(); // 语法糖初始化2)带参数
Car(this.name, this.model); // 语法糖初始化 Car(String name, String model) : name = name, model = model;3)调用时机
// 不带参数 final car1 = Car(); // 带参数 final car2 = Car('Tesla', 'Model 3');实例方法
class Car { void execute() { // do something } } final car = Car(); car.execute();Getter/Setter方法
class Car { late double _right; set right(double value) => _right = value; double get right => _right; void execute() { this.right = 3.14; // set print('${this.right}'); // get } }类继承
class BydCar extends Car { @override void execute() { super.execute(); // 调用父类方法 } }class BydCar extends Car { @override void execute() { // 方法重写 } }接口抽象
abstract class CarInterface { void drive(); }接口继承
abstract class BydInterface extends CarInterface { void automaticParking(); }接口实现
class BydCar extends Car implements BydInterface { void drive() { // drive } void automaticParking() { // automatic parking } }静态属性
// 声明 class EventConstants { static const bool AVAILABLE = true; static const String LOADD_EVENT = 'onLoad'; static const String UNLOAD_EVENT = 'onUnload'; } // 应用 const available = EventConstants.AVAILABLE;静态方法
// 声明 class DeviceUtils { static String getDeviceName() { return 'iphone 16 pro max'; } } // 应用 const deviceName = DeviceUtils.getDeviceName();七、引用
导入系统核心库。
import 'dart:io'; import 'dart:ui' as ui; final double kScreenWidth = ui.window.physicalSize.width/ui.window.devicePixelRatio;导入公共组件和模块代码。
import 'package:sqflite/sqflite.dart'; import 'package:test_module/test.dart';本文参考于Dart中文网:Dart开发语言