Dart 基础7 —— 库, Null safety,类型断言,late,required

101 阅读1分钟
  • 自定义库 import 'lib/xxx.dart '

  • 系统内置库

import "dart:math";

void main() {
  print(min(12,23));
  print(max(12,29));
}
  • 使用第三方库(pub 包管理系统)
  1. 网址: pub.dev/
  2. 具体步骤:
1 在项目根目录下新建一个pubspec.yaml
2 在pubspec.yaml文件中配置名称.描述、依赖等信息
3 运行pub get 安装包到本地
4 引入库 import ''
  • 库的重命名 import '' as ''

  • 部分导入

import './math.dart' show get();
import './math.dart' hide get();

  • 延迟加载(懒加载) 好处:减少App的启动时间 关键字: deferred as

  • Null Safety(可空类型)String?

void main() {
  String? name = 'za';
  name = null;
  print(name);
}
String? getData(params) {
  if (params != null) {
    return 'hello--';
  }
  return null;
}

void main() {
  var res = getData(123);
  print(res);
}
  • !类型断言
void getLength(String? str) {
  try {
    print(str!.length);
  } catch (e) {
    print('str is null');
  }
}

void main() {
//  类型断言:如果str != null,打印str的长度,否则抛出异常
  getLength(null);
  getLength('abx');
}

  • 延迟初始化 late
class Person {
  late String name;
  void setName(String name) {
    this.name = name;
  }

  String getName() {
    return this.name;
  }
}

void main() {
  Person p = new Person();
  p.setName('zs');
  print(p.getName());
}
  • required 关键字 下面的name为必须传入的命名参数 age可以传可以不传
class Person {
  String name;
  int? age; // 可为空
  Person({required this.name, this.age});

  String getInfo() {
    return '${this.name} === ${this.age}';
  }
}

void main() {
  Person p = new Person(name: 'ls', age: 20);
  print(p.getInfo());
  
  Person p2 = new Person(name: 'zs');
  print(p2.getInfo());
}