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
}
相关推荐
hnlucky9 分钟前
redis 数据类型新手练习系列——Hash类型
数据库·redis·学习·哈希算法
Invinciblenuonuo18 分钟前
FreeRTOS学习笔记【10】-----任务上下文切换
笔记·学习
好奇龙猫19 分钟前
日语学习-日语知识点小记-构建基础-JLPT-N4阶段(11): てあります。
学习
2501_915373881 小时前
Node.js 学习入门指南
学习·node.js
玫瑰花开一片一片2 小时前
Flutter IOS 真机 Widget 错误。Widget 安装后系统中没有
flutter·ios·widget·ios widget
绵绵细雨中的乡音2 小时前
Linux进程学习【基本认知】
linux·运维·学习
hepherd3 小时前
Flutter 环境搭建 (Android)
android·flutter·visual studio code
我的golang之路果然有问题3 小时前
快速了解redis,个人笔记
数据库·经验分享·redis·笔记·学习·缓存·内存
Angindem5 小时前
SpringClound 微服务分布式Nacos学习笔记
分布式·学习·微服务