zoukankan      html  css  js  c++  java
  • 11Dart 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
    }
    
  • 相关阅读:
    ASP.NET CORE 使用Consul实现服务治理与健康检查(2)——源码篇
    ASP.NET CORE 使用Consul实现服务治理与健康检查(1)——概念篇
    Asp.Net Core 单元测试正确姿势
    如何通过 Docker 部署 Logstash 同步 Mysql 数据库数据到 ElasticSearch
    Asp.Net Core2.2 源码阅读系列——控制台日志源码解析
    使用VS Code 开发.NET CORE 程序指南
    .NetCore下ES查询驱动 PlainElastic .Net 升级官方驱动 Elasticsearch .Net
    重新认识 async/await 语法糖
    EF添加
    EF修改部分字段
  • 原文地址:https://www.cnblogs.com/johu/p/15705066.html
Copyright © 2011-2022 走看看