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
}
相关推荐
Alsn861 小时前
Windows 安装 Ollama 及本地模型部署
学习·1024程序员节
欣欣之王来了2 小时前
原始HTML插值:v-html指令的使用与安全风险
前端·学习·架构·项目·vue3教程
好的佩奇4 小时前
Dart 之模式
android·flutter·dart
知识分享小能手4 小时前
C学习教程,从入门到精通,C语言学生信息管理系统 — 知识点详解(18)
c语言·学习·1024程序员节
破芽5 小时前
learn-claude-code-s05-s11-学习笔记
笔记·学习
pipixia200335 小时前
C++ 面试高频:namespace 的 6 个知识点,从 using 到匿名命名空间
c语言·学习·算法·嵌入式·命名空间·c++面试·匿名命名空间
每天题库5 小时前
汽车维修工等级考试题库 理论实操核心考点一次梳理清
学习·安全·考试·题库·考证
神也畏惧菠萝5 小时前
想要学习Agent应用开发?:2026 AI Agent开发全栈通关路线
学习·langgraph·mcp协议·agent开发·rag架构·prompt高级工程
淡淡的香烟6 小时前
Flutter实现多语言切换
android·flutter·1024程序员节
程序猿乐锅6 小时前
【从0-1学习Python | 第七篇】Python 面向对象基础
开发语言·笔记·后端·python·学习·1024程序员节