目錄

起步課程:編寫命令列和伺服器端應用

跟著下面這些步驟開始使用 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

Once you’re ready to move beyond DartPad and 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):

    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

接下來做什麼?

檢索這些資源:

如果你在這一步無法繼續進行,可以從 社群和幫助 中查詢幫助。