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
}
相关推荐
jiejiejiejie_3 小时前
Flutter for OpenHarmony 心情日记功能实战指南
flutter·华为
kuinnebula3 小时前
RTSP学习
学习
jiejiejiejie_3 小时前
Flutter for OpenHarmony 倒计时功能实战开发
flutter
Math_teacher_fan4 小时前
Flutter 跨平台开发实战:鸿蒙与音乐律动艺术(六)、Lissajous 利萨茹曲线:频率耦合的轨迹艺术
flutter·ui·数学建模·华为·harmonyos·鸿蒙系统
里欧跑得慢4 小时前
17. Flutter Hero动画实现:让界面过渡更加优雅
前端·css·flutter·web
北顾笙9804 小时前
LLM学习-day04
学习
liulian09165 小时前
Flutter for OpenHarmony 跨平台开发:秒表功能实战指南
flutter
xmdy58665 小时前
Flutter+开源鸿蒙实战|智安盾电商溯源平台Day3 溯源查询逻辑+鸿蒙网络请求适配
flutter·开源·harmonyos
lzj_pxxw6 小时前
W25Q64存储芯片 软件设计刚需常识
stm32·单片机·嵌入式硬件·mcu·学习
maaath6 小时前
【maaath】Flutter 跨平台日历日程应用开发实战
flutter·华为·harmonyos