経緯
FlutterでJSONいじるのにjson_serializableというパッケージを試す際、Dartのbuild_runner
のエラーにハマったのでメモ。
Dartのbuild_runnerでエラー
json_serializable
を使うためのパッケージを追加し、モデルクラスを作成。build_runner
コマンドで自動生成を走らせようとすると、エラーになってしまいました。
wiz:json_serializable_sample unsoluble_sugar$ flutter packages pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 368ms
[INFO] Initializing inputs
[INFO] Reading cached asset graph...
[INFO] Reading cached asset graph completed, took 75ms
[INFO] Checking for updates since last build...
[INFO] Checking for updates since last build completed, took 781ms
[INFO] Running build...
[SEVERE] json_serializable:json_serializable on lib/ user.dart:
NoSuchMethodError: The getter 'element' was called on null.
Receiver: null
Tried calling: element
[INFO] 6.8s elapsed, 2/3 actions completed.
[INFO] Running build completed, took 7.4s
[INFO] Caching finalized dependency graph...
[INFO] Caching finalized dependency graph completed, took 35ms
[SEVERE] Failed after 7.5s
pub finished with exit code 1
NoSuchMethodError: The getter 'element' was called on null.
で「pub finished with exit code 1」となり、無事詰む/(^o^)\
原因
ググっていろいろ調べてみるも、全然わからん。
クラス名とファイル名が一致してなかったりするのかなぁ…
んあああああああああああああああああああ!!!!
ファイル名の先頭にスペースが混入していたという凡ミス\(^o^)/
解決
ファイル名を修正して再度build_runner
を走らせます。
$ flutter packages pub run build_runner build
wiz:json_serializable_sample unsoluble_sugar$ flutter packages pub run build_runner build
[INFO] Generating build script...
[INFO] Generating build script completed, took 384ms
[INFO] Initializing inputs
[INFO] Reading cached asset graph...
[INFO] Reading cached asset graph completed, took 74ms
[INFO] Checking for updates since last build...
[INFO] Checking for updates since last build completed, took 810ms
[INFO] Running build...
[INFO] Running build completed, took 856ms
[INFO] Caching finalized dependency graph...
[SEVERE] The outputs field in json_serializable_sample|lib/user.g.dart references a non-existent asset json_serializable_sample|lib/ user.json_serializable.g.part and will corrupt the asset graph. If you encounter this error please copy the details from this message and add them to https://github.com/dart-lang/build/issues/1804.
[INFO] Caching finalized dependency graph completed, took 32ms
[INFO] Succeeded after 897ms with 2 outputs (3 actions)
今度は成功。
無事にモデルクラスに対応したファイルが自動生成されました。
NoSuchMethodErrorというメッセージから、ファイル名に問題があるという原因にたどり着くのはなかなか難しいですね…
コマンドの実行ログでファイルパスが出てるので、よく見れば気付くミスでした。
[INFO] Running build...
[SEVERE] json_serializable:json_serializable on lib/ user.dart:
凡ミスへの反省の念も込めて書き残しておきます。