Johu

11-Dart 2.13之后的新特性

本篇从大地老师《Dart 入门实战教程》学习整理而来。

Null safety

Flutter2.2.0 之后的版本都要求使用 Null safety。

  • 目的是帮助开发者避免一些日常开发中很难被发现的错误,可以改善性能。
    • ? 可空类型
    • ! 类型断言

可空类型

  • 在类型后面加上 ? 表示该类型可空
void main(args) {
  // int a = 123; // 非空的 int 类型
  int? a = 123; // 可空的 int 类型
  a = null; // 没法将 null 赋值给非空类型 a,可以将 null 赋值给可空类型
  print(a);  // null

  List<String>? li = ['12', '213', 'ew'];
  li = null;
  print(li); // null

  // 方法定义可空类型
  String? getData(url) {
    if (url != null) {
      return "this is a url";
    }
    return null;
  }

  print(getData(null)); // null
}

类型断言

  • !
// 类型断言的正确用法 try catch
void printLength(String? str) {
  try {
    print(str!.length);
  } catch (e) {
    print('str is null');
  }
}

void main(args) {
  printLength(null); // str is null

  // 类型断言:如果str不等于 null 会打印 str 的长度,如果等于 null 会抛出异常
  String? str = "this is str";
  str = null;
  print(str!.length); // 抛出异常
}

late 关键词

  • late 关键词主要用于延迟初始化
class Person {
  // 报错:非空实例字段'name'必须初始化。加上 late 表示稍后初始化
  late String name;
  late int age;
  void setName(String name, int age) {
    this.name = name;
    this.age = age;
  }
}

abstract class Db {
  // 抽象类中也可使用
  late String url;
}

require 关键词

  • 如果不指定默认值则需要在传参前面加入 require,表示这个参数必须传入
String printUserInfo(String username, {required int age, required String sex}) {
  return '姓名$username---性别$sex---年龄$age';
}

class Person {
  String? name;
  int age;
  // 表示实例化的时候 name 可传可不传,但是 age 必须传入
  Person({this.name, required this.age});

  String getName() {
    return "${this.name}---${this.age}";
  }
}

void main() {
  print(printUserInfo('战三', age: 32, sex: '女')); // 姓名战三---性别女---年龄32

  Person p = new Person(age: 32);
  print(p.getName()); // null---32
}
posted @ 2021-12-18 15:02  Johu  阅读(86)  评论(0编辑  收藏  举报