本站公告

晚上好😎🫰

今天是2025年1月4日星期六

Santos
Creator @999-Blog.pro
https://github.com/SantosXXXE

Skip to content

Dart 是一个易用、可移植且高效的语言,适用于在全平台开发高质量的应用程序

更新: 2024/11/3 字数: 0 字 时长: 0 分钟

高易用性

为基于事件驱动的用户界面提供成熟且完备的 异步-等待 体系,同时配备了 基于 isolate 的并发

使用 健全的空安全、 集合内的条件语句 以及模式匹配 等特性编写安全简洁的代码

语法相近、易学易用的编程语言

研发生产力提高

在正在运行的应用中使用 热重载,从而快速并持续地应用更改,并且立刻看到更改的效果

在编写代码时享受灵活的类型系统,以及强大且 可配置的静态分析工具

使用你选择的代码编辑器进行 性能分析、 日志记录以及 调试

在全平台极速运行

使用 AOT 编译为机器码, 极速启动 你的应用

使用完整、成熟且快速的 JavaScript & WebAssembly 编译器 为 Web 平台编译应用

仅用一种语言即可编写应用的 后端代码

变量

虽然 Dart 是 代码类型安全 的语言,你仍然可以用 var 来定义变量,而不用显式指定它们的类型。由于其支持类型推断,因此大多数变量的类型会由它们的初始化内容决定

dart
var name = 'Voyager I';
var year = 1977;
var antennaDiameter = 3.7;
var flybyObjects = ['Jupiter', 'Saturn', 'Uranus', 'Neptune'];
var image = {
  'tags': ['saturn'],
  'url': '//path/to/saturn.jpg'
};

流程控制语句

Dart 支持常用的流程控制语句:

dart
if (year >= 2001) {
  print('21st century');
} else if (year >= 1901) {
  print('20th century');
}

for (final object in flybyObjects) {
  print(object);
}

for (int month = 1; month <= 12; month++) {
  print(month);
}

while (year < 2016) {
  year += 1;
}

函数

我们建议 为每个函数的参数以及返回值都指定类型:

dart
int fibonacci(int n) {
  if (n == 0 || n == 1) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}

var result = fibonacci(20);

=> (胖箭头) 简写语法用于仅包含一条语句的函数。该语法在将匿名函数作为参数传递时非常有用:

dart
flybyObjects.where((name) => name.contains('turn')).forEach(print);

上面的示例除了向你展示了匿名函数(上例中传入 where() 函数的参数即是一个匿名函数)外,还向你展示了将函数作为参数使用的方式:上面示例将顶层函数 print() 作为参数传给了 forEach() 函数。

注释

Dart 通常使用双斜杠 // 作为注释的开始。

dart
// This is a normal, one-line comment.

/// This is a documentation comment, used to document libraries,
/// classes, and their members. Tools like IDEs and dartdoc treat
/// doc comments specially.

/* Comments like these are also supported. */

导入 (Import)

使用 import 关键字来访问在其它库中定义的 API。

dart
// Importing core libraries
import 'dart:math';

// Importing libraries from external packages
import 'package:test/test.dart';

// Importing files
import 'path/to/my_other_file.dart';

类 (Class)

下面的示例中向你展示了一个包含三个属性、两个构造函数以及一个方法的类。其中一个属性不能直接赋值,因此它被定义为一个 getter 方法(而不是变量)。该方法使用字符串插值来打印字符串文字内变量的字符串

dart
class Spacecraft {
  String name;
  DateTime? launchDate;

  // Read-only non-final property
  int? get launchYear => launchDate?.year;

  // Constructor, with syntactic sugar for assignment to members.
  Spacecraft(this.name, this.launchDate) {
    // Initialization code goes here.
  }

  // Named constructor that forwards to the default one.
  Spacecraft.unlaunched(String name) : this(name, null);

  // Method.
  void describe() {
    print('Spacecraft: $name');
    // Type promotion doesn't work on getters.
    var launchDate = this.launchDate;
    if (launchDate != null) {
      int years = DateTime.now().difference(launchDate).inDays ~/ 365;
      print('Launched: $launchYear ($years years ago)');
    } else {
      print('Unlaunched');
    }
  }
}

你可以像下面这样使用 Spacecraft 类:

dart
var voyager = Spacecraft('Voyager I', DateTime(1977, 9, 5));
voyager.describe();

var voyager3 = Spacecraft.unlaunched('Voyager III');
voyager3.describe();

枚举类型 (Enum)

枚举类型的取值范围是一组预定义的值或实例。

dart
enum PlanetType { terrestrial, gas, ice }

下面是一个增强型枚举的示例,定义了一组行星类的常量实例,即太阳系的行星:

dart
/// Enum that enumerates the different planets in our solar system
/// and some of their properties.
enum Planet {
  mercury(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
  venus(planetType: PlanetType.terrestrial, moons: 0, hasRings: false),
  // ···
  uranus(planetType: PlanetType.ice, moons: 27, hasRings: true),
  neptune(planetType: PlanetType.ice, moons: 14, hasRings: true);

  /// A constant generating constructor
  const Planet(
      {required this.planetType, required this.moons, required this.hasRings});

  /// All instance variables are final
  final PlanetType planetType;
  final int moons;
  final bool hasRings;

  /// Enhanced enums support getters and other methods
  bool get isGiant =>
      planetType == PlanetType.gas || planetType == PlanetType.ice;
}

你可以这样使用 Planet 枚举:

dart
final yourPlanet = Planet.earth;

if (!yourPlanet.isGiant) {
  print('Your planet is not a "giant planet".');
}

扩展类(继承)

Dart 支持单继承

dart
class Orbiter extends Spacecraft {
  double altitude;

  Orbiter(super.name, DateTime super.launchDate, this.altitude);
}

Mixins

Mixin 是一种在多个类层次结构中重用代码的方法。下面的是声明一个 Mixin 的做法:

dart
mixin Piloted {
  int astronauts = 1;

  void describeCrew() {
    print('Number of astronauts: $astronauts');
  }
}

现在你只需使用 Mixin 的方式继承这个类就可将该类中的功能添加给其它类。

dart
class PilotedCraft extends Spacecraft with Piloted {
  // ···
}

自此,PilotedCraft 类中就包含了 astronauts 字段以及 describeCrew() 方法。

接口和抽象类

所有的类都隐式定义成了一个接口。因此,任意类都可以作为接口被实现。

dart
class MockSpaceship implements Spacecraft {
  // ···
}

你可以创建一个被任意具体类扩展(或实现)的抽象类。抽象类可以包含抽象方法(不含方法体的方法)

dart
abstract class Describable {
  void describe();

  void describeWithEmphasis() {
    print('=========');
    describe();
    print('=========');
  }
}

任意一个扩展了 Describable 的类都拥有 describeWithEmphasis() 方法,这个方法又会去调用实现类中实现的 describe() 方法

异步

使用 asyncawait 关键字可以让你避免回调地狱 (Callback Hell) 并使你的代码更具可读性。

dart
const oneSecond = Duration(seconds: 1);
// ···
Future<void> printWithDelay(String message) async {
  await Future.delayed(oneSecond);
  print(message);
}

上面的方法相当于:

dart
Future<void> printWithDelay(String message) {
  return Future.delayed(oneSecond).then((_) {
    print(message);
  });
}

如下一个示例所示,asyncawait 关键字有助于使异步代码变得易于阅读

dart
Future<void> createDescriptions(Iterable<String> objects) async {
  for (final object in objects) {
    try {
      var file = File('$object.txt');
      if (await file.exists()) {
        var modified = await file.lastModified();
        print(
            'File for $object already exists. It was modified on $modified.');
        continue;
      }
      await file.create();
      await file.writeAsString('Start describing $object in this file.');
    } on IOException catch (e) {
      print('Cannot create description for $object: $e');
    }
  }
}

你也可以使用 async* 关键字,其可以为你提供一个可读性更好的方式去生成 Stream

dart
Stream<String> report(Spacecraft craft, Iterable<String> objects) async* {
  for (final object in objects) {
    await Future.delayed(oneSecond);
    yield '${craft.name} flies by $object';
  }
}

异常

使用 throw 关键字抛出一个异常:

dart
if (astronauts == 0) {
  throw StateError('No astronauts.');
}

使用 try 语句配合 oncatch(两者也可同时使用)关键字来捕获一个异常:

dart
Future<void> describeFlybyObjects(List<String> flybyObjects) async {
  try {
    for (final object in flybyObjects) {
      var description = await File('$object.txt').readAsString();
      print(description);
    }
  } on IOException catch (e) {
    print('Could not describe object: $e');
  } finally {
    flybyObjects.clear();
  }
}

注意上述代码是异步的;同步代码以及异步函数中得代码都可以使用 try 捕获异常。

结论

Dart语言的这些特性使其适合用于开发高性能、跨平台的应用程序,无论是在移动设备、Web还是后端。Dart的简洁性和强大的语言特性使其成为了现代软件开发的有力工具。

如果你发现这篇指南有用,或者有改进建议,请随时联系我们或参与讨论。🎉 🎉 🎉