2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Flutter】freezed なクラスを一瞬で出力するVSCodeスニペット

Posted at

Riverpod + freezed 便利に使っています。ただ、freezed のクラスを新しく書く時に、どこかからコピーして...クラス名を書き換えて...というのが割と面倒でしたのでVSCodeのスニペット化しました。定型的な作業はできる限り効率化したいですよね。

何ができるようになる?

以下のようなfreezed クラスを frz という文字を打つだけで作成できます。
import文も含めて生成されるので、自分の作りたいクラス名とフィールド名を追加する作業だけに集中できます。
part XXX のXXXには今のファイル名が自動で補完されます

import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';
part 'XXX.freezed.dart';

@freezed
class DataClass with _$DataClass {
  const factory DataClass({
    @Default(0) int counter, // Add your fields here
  }) = _DataClass;
}

インストール

  • Cmd + Shift + P を押して(Macの場合) Configure User Snippet を入力、選択
  • dart.json があれば選択、なければ、New Global Snippet File を選択し dart.json を作成

開いたJSONファイルに以下を追加します。

	"Freezed class template": {
		"prefix": "frzclass",
		"description": "Create a Freezed class",
		"body": [
			"import 'package:freezed_annotation/freezed_annotation.dart';",
			"import 'package:flutter/foundation.dart';",
			"part '${TM_FILENAME_BASE}.freezed.dart';",
			"",
			"@freezed",
			"class ${1:DataClass} with _$${1:DataClass} {",
			"\tconst factory ${1:DataClass}({",
			"\t\t@Default(0) int counter, // Add your fields here",
			"\t}) = _${1:DataClass};",
			"}"
		]
	},

使い方

  • .dartファイルを編集中に、 frz.. と打つと frzclass が候補に出ますので選択
  • freezed のクラステンプレートが入力されます
  • テンプレートに入っている DataClass を自分が作りたいクラス名に変更
  • 必要なフィールドも適宜追加します(デフォルトで入ってるcounter変数はサンプルなので削除ください)
  • あとは flutter pub run build_runner build を実行してコード生成すれば完了です。
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?