📚 目录
- 1. Dart 基础类型系统
- 1.1 基本数据类型
- 1.2 可空类型与空安全
- 1.3 集合类型详解
- 1.4 字符串类型进阶
- 1.5 数字类型详解
- 2. Dart 高级类型系统
- 2.1 函数类型与回调
- 2.2 泛型类型系统
- 2.3 类与接口类型
- 2.4 枚举类型
- 2.5 扩展类型
- 2.6 混入类型
- 2.7 异步类型
- 3. GetX 响应式类型系统
- 3.1 基础响应式类型
- 3.2 Rx 类型详解
- 3.3 响应式集合类型
- 3.4 响应式状态管理
- 3.5 响应式计算属性
- 4. GetX 控制器类型系统
- 4.1 基础控制器类型
- 4.2 泛型控制器
- 4.3 生命周期控制器
- 4.4 专用控制器类型
- 5. GetX 依赖注入类型
- 5.1 服务注册类型
- 5.2 依赖获取类型
- 5.3 绑定类型
- 6. GetX 路由与导航类型
- 7. GetX 工具类型
- 7.1 Worker 类型
- 7.2 响应式监听器
- 7.3 国际化类型
- 8. 实际应用场景
- 8.1 表单处理类型
- 8.2 网络请求类型
- 8.3 数据持久化类型
- 8.4 主题与样式类型
- 9. 性能优化与最佳实践
- 9.1 类型安全最佳实践
- 9.2 内存管理
- 9.3 性能优化技巧
- 10. 常见错误与解决方案
1. Dart 基础类型系统
1.1 基本数据类型
数字类型详解
int age = 25;
int hexValue = 0xFF;
int binaryValue = 0b1010;
int bigNumber = 9223372036854775807;
double price = 99.99;
double scientific = 1.42e5;
double infinity = double.infinity;
double notANumber = double.nan;
num value = 42;
num result = value.isEven ? value : value + 1;
String numberStr = '123';
int parsed = int.parse(numberStr);
double parsedDouble = double.parse('123.45');
int? tryParsed = int.tryParse('invalid');
字符串类型详解
String name = 'Flutter';
String description = "Dart 编程语言";
String multiLine = '''
这是一个
多行字符串
支持换行
''';String rawString = r'原始字符串 \n 不会转义';
String greeting = 'Hello, $name!';
String calculation = '结果是: ${2 + 3}';
String text = 'Hello World';
String upper = text.toUpperCase();
String lower = text.toLowerCase();
List<String> words = text.split(' ');
String joined = words.join('-');
bool contains = text.contains('World');
String substring = text.substring(0, 5);
String emoji = '🚀 Flutter 开发';
String chinese = '你好世界';
布尔类型
bool isActive = true;
bool isCompleted = false;
bool result = isActive && !isCompleted;
bool orResult = isActive || isCompleted;
bool? isOptional;
bool safeValue = isOptional ?? false;
1.2 可空类型与空安全
空安全基础
String? nullableName;
int? nullableAge;
List<String>? nullableList;
String nonNullName = 'Flutter';
late String lateInitialized;
String name = nullableName!;
String displayName = nullableName ?? 'Unknown';
int count = nullableAge ?? 0;
nullableName ??= 'Default Name';
条件访问操作符
int? length = nullableName?.length;
String? upperCase = nullableName?.toUpperCase();
String? result = user?.profile?.name?.toUpperCase();
String? firstChar = nullableName?[0];
int? firstElement = nullableList?[0];
void printLength() {nullableName?.length.toString();
}
空安全模式检查
void handleNullableValue(String? value) {if (value != null) {print(value.length); print(value.toUpperCase());}if (value?.isNotEmpty == true) {print('值不为空且不为空字符串');}if (value is String) {print(value.length); }
}
1.3 集合类型详解
List 列表类型
List<String> fruits = ['apple', 'banana', 'orange'];
List<int> numbers = [1, 2, 3, 4, 5];
List<dynamic> mixed = [1, 'hello', true, 3.14];
List<int> fixedList = List.filled(5, 0);
List<String> growableList = List.generate(3, (index) => 'item_$index');
fruits.add('grape');
fruits.addAll(['kiwi', 'mango']);
fruits.insert(1, 'pear');
fruits.remove('banana');
fruits.removeAt(0);
fruits.clear();
bool hasApple = fruits.contains('apple');
int index = fruits.indexOf('orange');
String? firstFruit = fruits.isNotEmpty ? fruits.first : null;
String? lastFruit = fruits.isNotEmpty ? fruits.last : null;
List<String> upperFruits = fruits.map((fruit) => fruit.toUpperCase()).toList();
List<String> filtered = fruits.where((fruit) => fruit.length > 5).toList();
String joined = fruits.join(', ');
List<String> immutableList = List.unmodifiable(fruits);
const List<int> constList = [1, 2, 3];
Map 映射类型
Map<String, int> scores = {'Alice': 95, 'Bob': 87, 'Charlie': 92};
Map<String, dynamic> user = {'name': 'John','age': 30,'isActive': true,'hobbies': ['reading', 'coding'],
};
scores['David'] = 88;
scores.update('Alice', (value) => value + 5);
scores.remove('Bob');
scores.clear();
bool hasAlice = scores.containsKey('Alice');
bool hasScore95 = scores.containsValue(95);
int? aliceScore = scores['Alice'];
int aliceScoreWithDefault = scores['Alice'] ?? 0;
scores.forEach((name, score) {print('$name: $score');
});
Map<String, String> stringScores = scores.map((key, value) => MapEntry(key, value.toString()),
);List<String> names = scores.keys.toList();
List<int> values = scores.values.toList();
Map<String, int> immutableMap = Map.unmodifiable(scores);
const Map<String, String> constMap = {'key': 'value'};
Set 集合类型
Set<String> uniqueNames = {'Alice', 'Bob', 'Charlie'};
Set<int> numbers = {1, 2, 3, 4, 5};
uniqueNames.add('David');
uniqueNames.addAll(['Eve', 'Frank']);
uniqueNames.remove('Bob');
Set<String> otherNames = {'Alice', 'Grace', 'Henry'};
Set<String> union = uniqueNames.union(otherNames);
Set<String> intersection = uniqueNames.intersection(otherNames);
Set<String> difference = uniqueNames.difference(otherNames);
bool hasAlice = uniqueNames.contains('Alice');
bool isEmpty = uniqueNames.isEmpty;
int count = uniqueNames.length;
List<String> nameList = uniqueNames.toList();
Set<String> filteredSet = uniqueNames.where((name) => name.length > 4).toSet();
1.4 字符串类型进阶
字符串缓冲区
StringBuffer buffer = StringBuffer();
buffer.write('Hello');
buffer.write(' ');
buffer.write('World');
String result = buffer.toString();
buffer.writeAll(['a', 'b', 'c'], '-');
buffer.writeln('新行');
正则表达式
RegExp emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
bool isValidEmail = emailRegex.hasMatch('user@example.com');
String text = 'Phone: 123-456-7890, Fax: 098-765-4321';
RegExp phoneRegex = RegExp(r'\d{3}-\d{3}-\d{4}');
Iterable<Match> matches = phoneRegex.allMatches(text);
String cleaned = text.replaceAll(phoneRegex, '[PHONE]');
1.5 数字类型详解
数学运算
import 'dart:math' as math;
double result = math.pow(2, 3).toDouble();
double sqrt = math.sqrt(16);
double sin = math.sin(math.pi / 2);
Random random = Random();
int randomInt = random.nextInt(100);
double randomDouble = random.nextDouble();
bool randomBool = random.nextBool();
import 'package:intl/intl.dart';
NumberFormat formatter = NumberFormat('#,##0.00');
String formatted = formatter.format(1234.567);
2. Dart 高级类型系统
2.1 函数类型与回调
函数类型定义
typedef Calculator = int Function(int a, int b);
typedef AsyncCallback = Future<void> Function();
typedef EventHandler<T> = void Function(T data);
typedef Validator<T> = bool Function(T value);
typedef Transformer<T, R> = R Function(T input);
typedef OptionalCallback = void Function([String? message]);
typedef NamedCallback = void Function({required String name, int? age});
void processData(List<int> data, int Function(int) processor) {final processed = data.map(processor).toList();print(processed);
}
Function createMultiplier(int factor) {return (int value) => value * factor;
}
T Function(T) compose<T>(T Function(T) f, T Function(T) g) {return (T x) => f(g(x));
}
回调模式
typedef SuccessCallback<T> = void Function(T data);
typedef ErrorCallback = void Function(String error);class ApiClient {void fetchData({required SuccessCallback<Map<String, dynamic>> onSuccess,required ErrorCallback onError,}) async {try {await Future.delayed(Duration(seconds: 1));onSuccess({'data': 'success'});} catch (e) {onError(e.toString());}}
}
typedef ProgressCallback = void Function(double progress);class FileUploader {Future<void> upload(String filePath, {ProgressCallback? onProgress,}) async {for (int i = 0; i <= 100; i += 10) {await Future.delayed(Duration(milliseconds: 100));onProgress?.call(i / 100.0);}}
}
2.2 泛型类型系统
基础泛型
class Box<T> {T _value;Box(this._value);T get value => _value;set value(T newValue) => _value = newValue;R transform<R>(R Function(T) transformer) {return transformer(_value);}
}
T getValue<T>(Map<String, dynamic> map, String key, T defaultValue) {final value = map[key];return value is T ? value : defaultValue;
}
class Pair<T, U> {final T first;final U second;Pair(this.first, this.second);@overrideString toString() => '($first, $second)';
}
泛型约束
class NumberBox<T extends num> {T _value;NumberBox(this._value);T get value => _value;bool get isPositive => _value > 0;T get absolute => _value.abs() as T;
}
abstract class Drawable {void draw();
}abstract class Clickable {void onClick();
}class InteractiveWidget<T extends Drawable & Clickable> {final T widget;InteractiveWidget(this.widget);void render() {widget.draw();}void handleClick() {widget.onClick();}
}
泛型集合操作
abstract class Repository<T, ID> {Future<T?> findById(ID id);Future<List<T>> findAll();Future<T> save(T entity);Future<void> delete(ID id);
}class UserRepository implements Repository<User, String> {final Map<String, User> _users = {};@overrideFuture<User?> findById(String id) async {return _users[id];}@overrideFuture<List<User>> findAll() async {return _users.values.toList();}@overrideFuture<User> save(User user) async {_users[user.id] = user;return user;}@overrideFuture<void> delete(String id) async {_users.remove(id);}
}
abstract class Factory<T> {T create();
}class UserFactory implements Factory<User> {@overrideUser create() => User(id: DateTime.now().toString(), name: 'New User');
}
2.3 类与接口类型
抽象类与接口
abstract class Shape {String get name;double calculateArea();double calculatePerimeter();void printInfo() {print('Shape: $name, Area: ${calculateArea()}');}
}
class Rectangle implements Shape {final double width;final double height;Rectangle(this.width, this.height);@overrideString get name => 'Rectangle';@overridedouble calculateArea() => width * height;@overridedouble calculatePerimeter() => 2 * (width + height);
}
class Square extends Rectangle {Square(double side) : super(side, side);@overrideString get name => 'Square';
}
混入 (Mixins)
mixin Flyable {double altitude = 0;void fly() {altitude = 100;print('Flying at altitude $altitude');}void land() {altitude = 0;print('Landed');}
}mixin Swimmable {double depth = 0;void swim() {depth = 10;print('Swimming at depth $depth');}void surface() {depth = 0;print('Surfaced');}
}
class Duck with Flyable, Swimmable {String name;Duck(this.name);void quack() {print('$name says quack!');}
}
mixin Walkable on Animal {void walk() {print('${this.name} is walking');}
}abstract class Animal {String get name;
}class Dog extends Animal with Walkable {@overrideString get name => 'Dog';
}
2.4 枚举类型
基础枚举
enum Status { pending, approved, rejected }
enum Planet {mercury(3.303e+23, 2.4397e6),venus(4.869e+24, 6.0518e6),earth(5.976e+24, 6.37814e6),mars(6.421e+23, 3.3972e6);const Planet(this.mass, this.radius);final double mass;final double radius;double get surfaceGravity => 6.67300E-11 * mass / (radius * radius);
}
enum HttpStatus {ok(200, 'OK'),notFound(404, 'Not Found'),internalServerError(500, 'Internal Server Error')