1、泛型类
class Cache<T> {final Map<String, T> _cache = {};void saveData(String key, T value) {_cache[key] = value;}T? getData(String key) {return _cache[key];}
}
void main() {Cache<int> cache1 = Cache();const String name1 = "Leon";cache1.saveData(name1, 18);print("name: $name1 age: ${cache1.getData(name1)}"); Cache<String> cache2 = Cache();const String name2 = "Alice";cache2.saveData(name2, "woman");print("name: $name2 sex: ${cache2.getData(name2)}");
}
2、泛型约束
class Person {String? name;int? age;Person(this.name, this.age);void display() {print("name: $name age: $age");}
}
class Student extends Person {String? _school;Student(name, age, this._school) : super(name, age);@overridevoid display() {print("name: $name age: $age school: $_school");}
}
class Member<T extends Person> {T? _person;Member(this._person);void show() {if (_person != null) {_person!.display();}}
}
void main() {Member<Student> member = Member(Student("Leon", 18, "hafo"));member.show();
}
3、补充:Flutter 的一些编程技巧
(1)空安全
void safeUse() {List? list;print("list: ${list?.length}");
}
(2)默认值
void defaultUse() {bool? isOpen;String result = '';if (isOpen ?? false) {result = '打开';} else {result = '关闭';}print("result: $result");
}
(3)集合判空
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]}");}}
}