当前位置: 首页 > news >正文

Dart 类型系统与 GetX 类型写法完整指南

📚 目录

  • 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 路由与导航类型
    • 6.1 路由参数类型
    • 6.2 页面绑定类型
  • 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; // 64位最大值// 浮点数类型
double price = 99.99;
double scientific = 1.42e5; // 科学计数法
double infinity = double.infinity;
double notANumber = double.nan;// 数字基类
num value = 42; // 可以是 int 或 double
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'); // 返回 null
字符串类型详解
// 基础字符串
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);// Unicode 支持
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'; // 不能为 null
late String lateInitialized; // 延迟初始化// 非空断言操作符 (!)
String name = nullableName!; // 确保不为空时使用,否则抛出异常// 空值合并操作符 (??)
String displayName = nullableName ?? 'Unknown';
int count = nullableAge ?? 0;// 空值赋值操作符 (??=)
nullableName ??= 'Default Name'; // 仅在为 null 时赋值
条件访问操作符
// 安全调用操作符 (?.)
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(); // 只有当 nullableName 不为 null 时才执行
}
空安全模式检查
void handleNullableValue(String? value) {// 类型提升 (Type Promotion)if (value != null) {// 在这个作用域内,value 被提升为非空类型print(value.length); // 不需要 ? 操作符print(value.toUpperCase());}// 空值检查的其他方式if (value?.isNotEmpty == true) {print('值不为空且不为空字符串');}// 使用 is 检查if (value is String) {print(value.length); // 类型提升为 String}
}

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); // [0, 0, 0, 0, 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 用于高效字符串拼接
StringBuffer buffer = StringBuffer();
buffer.write('Hello');
buffer.write(' ');
buffer.write('World');
String result = buffer.toString(); // "Hello World"// 批量操作
buffer.writeAll(['a', 'b', 'c'], '-'); // "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(); // 8.0
double sqrt = math.sqrt(16); // 4.0
double sin = math.sin(math.pi / 2); // 1.0// 随机数
Random random = Random();
int randomInt = random.nextInt(100); // 0-99
double randomDouble = random.nextDouble(); // 0.0-1.0
bool randomBool = random.nextBool();// 数字格式化
import 'package:intl/intl.dart';
NumberFormat formatter = NumberFormat('#,##0.00');
String formatted = formatter.format(1234.567); // "1,234.57"

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);String toString() => '($first, $second)';
}
泛型约束
// 类型约束
class NumberBox<T extends num> {T _value;NumberBox(this._value);T get value => _value;// 可以使用 num 的方法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 = {};Future<User?> findById(String id) async {return _users[id];}Future<List<User>> findAll() async {return _users.values.toList();}Future<User> save(User user) async {_users[user.id] = user;return user;}Future<void> delete(String id) async {_users.remove(id);}
}// 泛型工厂
abstract class Factory<T> {T create();
}class UserFactory implements Factory<User> {User 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);String get name => 'Rectangle';double calculateArea() => width * height;double calculatePerimeter() => 2 * (width + height);
}// 继承与重写
class Square extends Rectangle {Square(double side) : super(side, side);String 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 {String get name => 'Dog';
}

2.4 枚举类型

基础枚举
// 简单枚举
enum Status { pending, approved, rejected }// 增强枚举 (Dart 2.17+)
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')

相关文章:

  • yarn create vite报错:文件名、目录名或卷标语法不正确。 error Command failed.
  • 【嵌入式】鲁班猫玩法大全
  • E结构体基础.go
  • 01.线性代数是如何将复杂的数据结构转化为可计算的数学问题,这个过程是如何进行的
  • FPGA基础 -- Verilog 结构建模之端口的不同位宽处理机制
  • flink如何基于Pekko实现RPC调用
  • openKylin适配RISC-V高性能服务器芯片,携手睿思芯科共拓智算新蓝海
  • ROS学习之动作通信
  • LangChain4j入门学习项目
  • 解决Vue再浏览器的控制台中更新属性不生效
  • Zephyr boot
  • 电池自动点焊机:技术革新下的电池制造核心引擎
  • FastMCP框架进行MCP开发:(一)基础环境搭建及测试
  • 新生活的开启:从 Trae AI 离开后的三个月
  • 如何在 Windows 上实时显示键盘操作?
  • C++ 面向对象特性详解:继承机制
  • Oracle EBS R12.1.3无法打开WEBADI界面
  • WHAT - JavaScript bind vs call vs apply(包括在箭头函数中vs在普通函数中)
  • Windows 下 C++ 线程同步与异步有哪些方式
  • 优化 Python 爬虫性能:异步爬取新浪财经大数据
  • 网站备案费用多少/百度网站排名查询
  • 网站开发是什/googleseo服务公司
  • 电子商务网站建设与维护pdf/谷歌搜索引擎香港入口
  • 信贷网站开发/谷歌海外广告投放
  • 智能网站建设平台/在什么网站可以免费
  • 什么网站可以做长图攻略/公司网络推广服务