Flutter学习7 - Dart 泛型

1、泛型类

dart 复制代码
//泛型类
class Cache<T> {
  final Map<String, T> _cache = {};

  void saveData(String key, T value) {
    _cache[key] = value;
  }

  //泛型方法
  T? getData(String key) {
    return _cache[key];
  }
}
dart 复制代码
void main() {
  Cache<int> cache1 = Cache();
  const String name1 = "Leon";
  cache1.saveData(name1, 18);
  print("name: $name1   age: ${cache1.getData(name1)}"); //name: leon   age: 18


  Cache<String> cache2 = Cache();
  const String name2 = "Alice";
  cache2.saveData(name2, "woman");
  print("name: $name2  sex: ${cache2.getData(name2)}"); //name: Alice  sex: woman
}

2、泛型约束

dart 复制代码
class Person {
  String? name;
  int? age;

  Person(this.name, this.age);

  void display() {
    print("name: $name   age: $age");
  }
}
dart 复制代码
class Student extends Person {
  String? _school;

  Student(name, age, this._school) : super(name, age);

  @override
  void display() {
    print("name: $name   age: $age  school: $_school");
  }
}
dart 复制代码
//泛型约束:T 只能是 Person 的子类
class Member<T extends Person> {
  T? _person;

  Member(this._person);

  void show() {
    if (_person != null) {
      _person!.display();
    }
  }
}
dart 复制代码
void main() {
  Member<Student> member = Member(Student("Leon", 18, "hafo"));
  member.show(); //name: Leon   age: 18  school: hafo
}

3、补充:Flutter 的一些编程技巧

(1)空安全

dart 复制代码
//安全调用
void safeUse() {
  List? list;
  print("list: ${list?.length}"); //list: null
}

(2)默认值

dart 复制代码
//默认值
void defaultUse() {
  bool? isOpen;
  //默认值
  String result = '';
  if (isOpen ?? false) {
    //isOpen == true
    result = '打开';
  } else {
    //isOpen == false || isOpen == null
    result = '关闭';
  }

  print("result: $result"); //关闭
}

(3)集合判空

dart 复制代码
//集合判空
void emptyUse() {
  List list = [];
  list.add(0);
  list.add('');
  list.add(null);
  list.add(true);

  for (int i = 0; i < list.length; i++) {
    if ([0, '', null].contains(list[i])) {
      print("index: $i   value: 空");
    } else {
      print("index: $i   vaule: ${list[i]}");
    }
  }
  // index: 0   value: 空
  // index: 1   value: 空
  // index: 2   value: 空
  // index: 3   vaule: true
}
相关推荐
Star(up up up)5 小时前
Redis Windows 安装教程:使用Windows 的 Redis 压缩包
redis·笔记·学习·程序人生·云原生·学习方法·改行学it
乌暮7 小时前
Spring AOP 与 Spring 事务:用大白话彻底理解原理与实践
java·数据库·spring boot·后端·sql·学习·spring
传奇开心果编程11 小时前
【Flutter踩坑排雷】第28课:平台目录缺失与修复坑|`flutter create` 的“重建”与“覆盖”边界
android·flutter·ios·移动开发·跨平台·dart·声明式ui
蒸蒸yyyyzwd12 小时前
从邓明学习的后端笔记
笔记·学习
机器学习之心12 小时前
基于变量相关图与残差学习的 GCN 多变量回归方法——混凝土 28 天抗压强度预测
学习·回归·gcn
Rabitebla1 天前
【Linux】进程控制(十二) 自定义 Shell(二):内建命令与进程工作目录管理
linux·c++·笔记·学习·bash
Gary移动存储固件1 天前
eMMC5.1协议中文学习讲解(6.6.17~6.6.22.4.6)
学习·ufs·emmc·nand·存储固件
一个天蝎座 白勺 程序猿1 天前
别让收藏夹替你学习:我搭AI知识体系的完整方法,脚本直接拿去用
人工智能·学习·ai·ai学习
楚山之石1 天前
【Nat Biomed Eng】Connectome 2.0 超高梯度扫描仪:500 mT/m 与 600 T/m/s 把活体人脑微观结构分辨推进到亚微米级
图像处理·学习·数据分析·mri
坤坤子吖1 天前
Linux网络编程:TCP 粘包与半包问题,如何正确处理 TCP 流式数据?
linux·服务器·网络·笔记·网络协议·学习