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
}