torikatsu.dev

Flutterとかプログラミングとかガジェットとか書きます

【Flutter】Dartの実行環境を作る

こんにちは、とりかつ(torikatsu923)です。

Flutter開発をしていると、Dartの実行環境が欲しい時があります。 例えばFreezedのようなflutter sdkに依存しないDart onlyなパッケージを試したい時などが考えられます。

今回はDartの実行環境の作り方を紹介しようと思います。

目次

とりあえずHello worldしてみる

とりあえずdart runHello worldできるようにしてみます。

  1. main.dartを用意します。

main.dart

void main() {
  print('Hello world');
}
  1. main.dartを実行する

ターミナルで以下を実行します

$ dart run main.dart

f:id:torikatsu923:20220115191234p:plain

無事コンソールにHello Worldが表示されました。

しかしこのままだとパッケージを試したい時に不便です。 いつもならpub getとするところを、手でパッケージをダウンロードしてきてimportも頑張ってパスで指定する必要があります。

pub getできるようにする

pub getできるようにするためには手元のプロジェクトをパッケージにする必要があります。 Dartのプロジェクトの単位はパッケージで、最小構成は以下のようになります。

.
├── ./lib
│   └── ./lib/${パッケージ名}.dart
└── ./pubspec.yaml

ここでpubspec.yamlではnameでパッケージ名指定する必要があるため注意です。

今回はパッケージ名をplaygroundとするため、ファイルツリーとpubspec.yamlは以下のようになります。

.
├── ./lib
│   └── ./lib/playground.dart
└── ./pubspec.yaml

pubspec.yaml

name: playground

それでは実行してみます。

dart run ./lib/playground.dart

f:id:torikatsu923:20220115192829p:plain

無事に実行することができ、pub getもできるようになりました。

今のままでもいいですが、dart run ./lib/playground.dartのファイル指定が少し面倒です。

ファイル指定なしでdart runできるようにする

一旦dart runしてみます。

You should edit ~/Desktop/flutter_dev/playground/pubspec.yaml to contain an SDK constraint:

environment:
  sdk: '>=2.10.0 <3.0.0'

See https://dart.dev/go/sdk-constraint

エラーっぽいものが出てきました。僕の環境ではdart2.15.1なのですが、dart2以降はpubspec.yamldartのバージョンを指定する必要があるみたいです。

~/desktop/flutter_dev/playground
❯ dart --version    
Dart SDK version: 2.15.1 (stable) (Tue Dec 14 13:32:21 2021 +0100) on "macos_x64"

pubspec.yamlを次のようにして再度dart runしてみます。

pubspec.yaml

name: playground
environment:
  sdk: '>=2.10.0 <3.0.0'
~/desktop/flutter_dev/playground
❯ dart run   
Could not find `bin/playground.dart` in package `playground`.

ファイルがないと怒られました。ファイル無指定時のdart runのエントリーポイントはlib/playground.dartではなく、bin/playground.dartのようです。 なのでbin/playground.dartを作って再度dart runします。

bin/playground.dart

import 'package:playground/playground.dart' as playground;

void main() {
  playground.main();
}

ファイルツリー

.
├── ./bin
│   └── ./bin/playground.dart
├── ./lib
│   └── ./lib/playground.dart
└── ./pubspec.yaml

無事実行されました!

~/desktop/flutter_dev/playground
❯ dart run
Building package executable...
Built playground:playground.
Hello World

【必殺技】dart createに頼る

ここまで手でpubspec.yaml等を作成してきました。 実はここまでの手順は以下のコマンドで一発でいけます。

dart create ${パッケージ名}

f:id:torikatsu923:20220115195507p:plain

めっちゃ楽ですね...

おわりに

今回はDartの実行環境の作り方を紹介しました。 普段Flutter触ってるけどDartのプロジェクト作り方わからんって人の助けになればと思います。