目录

起步教程:编写命令行和服务端应用

跟着下面这些步骤开始使用 Dart SDK 来开发命令行和服务器应用。首先你将在浏览器中运行 Dart 编程语言而不需要下载它。接着,你需要安装 Dart SDK 并尝试开发一个小程序,然后使用 Dart VM 运行它。最后你将使用一个 AOT()编译器将你刚才完成的程序编译为可以被 Dart 运行时执行的原生机器码。

1. 在 DartPad 中运行 Dart 代码

#

你可以使用 DartPad 来简单地尝试 Dart 编程语言和 API 且不需要下载任何东西。

例如,下面这个内嵌的 DartPad 可以让你尝试一个简单的 Hello World 程序代码。点击运行来运行应用;控制台输出的内容位于代码块下方。你可以尝试更改源代码,比如更改问候语或者其它的一些语句。


void main() {
  print('Hello, World!');
}

更多信息:

2. 安装 Dart

#

To develop real apps, you need an SDK. You can either download the Dart SDK directly (as described below) or download the Flutter SDK, which includes the full Dart SDK.

Use Chocolatey to install a stable release of the Dart SDK.

To install the Dart SDK:

C:\> choco install dart-sdk

You can use APT to install the Dart SDK on Linux.

  1. Perform the following one-time setup:

    $ sudo apt-get update
    $ sudo apt-get install apt-transport-https
    $ wget -qO- https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo gpg --dearmor -o /usr/share/keyrings/dart.gpg
    $ echo 'deb [signed-by=/usr/share/keyrings/dart.gpg arch=amd64] https://storage.googleapis.com/download.dartlang.org/linux/debian stable main' | sudo tee /etc/apt/sources.list.d/dart_stable.list
  2. Install the Dart SDK:

    $ sudo apt-get update
    $ sudo apt-get install dart

With Homebrew, installing Dart is easy.

$ brew tap dart-lang/dart
$ brew install dart

3. 创建一个小应用

#

使用 dart create 命令,以 console-full 模板创建一个命令行应用:

$ dart create -t console cli

该命令会创建一个包含下述信息的 Dart 应用:

  • 一个主要的 Dart 源文件,bin/cli.dart,该文件包含一个顶层 main() 函数。该函数是你应用的入口。

  • 一个额外的 Dart 文件,lib/cli.dart,包含一些功能性的函数方法,这些函数方法将会导入到 cli.dart 文件中。

  • 一个 pubspec 文件,pubspec.yaml,包含应用的元数据,包括应用依赖的 package 信息以及所需的版本等。

4. 运行应用

#

想要从命令行运行应用,请使用 dart run 命令在应用的根目录运行 Dart VM:

$ cd cli
$ dart run
Hello world: 42!

If you want to run the app with debugging support, see Dart DevTools.

5. 修改应用

#

现在我们来自定义刚才你所创建的应用。

  1. 编辑 lib/cli.dart 以返回一个不同的结果。例如,将先前的值除以2。(关于 ~/ 的详情请查看 Arithmetic operators):

    dart
    int calculate() {
      return 6 * 7 ~/ 2;
    }
  2. 保存你刚才所做的改变。

  3. 重新运行你应用的入口 main 函数:

    $ dart run
    Hello world: 21!

更多信息:开发命令行应用

6. 编译成正式产品

#

上面的示例步骤我们使用的是 Dart VM(即 dart 命令)运行的应用。 Dart VM 针对快速增量编译进行了优化,以便在开发过程中提供即时的响应。现在你的小应用已经完成,是时候 AOT 优化编译你的 Dart 代码为原生机器代码了。

使用 dart compile 工具将程序 AOT 编译成机器代码:

$ dart compile exe bin/cli.dart

看看编译后的程序启动有多快:

$ time bin/cli.exe
Hello world: 21!

real	0m0.016s
user	0m0.008s
sys	0m0.006s

接下来做什么?

#

检索这些资源:

如果你在这一步无法继续进行,可以从 社区和帮助 中查找帮助。