LoginSignup
9
8

More than 3 years have passed since last update.

Android StudioでのFlutter開発でfreezed用のLive Templateを準備する

Posted at

Live Template のおすすめ

Dart には data class が無いので、JSONをシリアライズ・デシリアライズしようとすると、ゴリゴリコードが必要になってきます。

そこで、freezedを使うんですが、なかなか覚えるようなコードではないので、Live Templateを使いましょうという話です。

Live Template の設定箇所

環境設定 Android Studio > Preferences...Editor > Live Templates で、Flutterを選択して "➕" ボタンをクリックします。

スクリーンショット 2020-09-16 15.16.25.png

設定内容

スクリーンショット 2020-09-16 15.28.01.png

設定項目 設定内容 備考
Abbreviation freezed 補完する際に入力する文字列なので、自分でわかりやすいものを
Description Create freezed class これも自分でわかりやすいものを
Template text テンプレート文字列 下記(Template text)参照
Edit variables テンプレート変数 下記(Variables)参照
Application in Dart: top-level トップレベルでしか使わないので
Expand with Default (Tab) 自分の好みの設定で
Reformat according to style non check 自分の好みの設定で
Shorten FQ names check 自分の好みの設定で

Template text

import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part '$FILE_NAME$.freezed.dart';
part '$FILE_NAME$.g.dart';

@freezed
abstract class $CLASS_NAME$ with _$$$CLASS_NAME$ {
  const factory $CLASS_NAME$({
    @required int id,
    @JsonKey(name: 'image_url') @required String imageUrl,
  }) = _$CLASS_NAME$;

 factory $CLASS_NAME$.fromJson(Map<String, dynamic> json) => _$$$CLASS_NAME$FromJson(json);
}

※ 変数 id, imageUrl の宣言部分は、@JsonKey(name: 'xxxxx') の書き方を都度調べるのが面倒なため、複製用として入れているものです。不要な方は削除してください。

Variables

スクリーンショット 2020-09-16 15.34.49.png

Name Expression Default value Skip if defined
FILE_NAME fileNameWithoutExtension() fileNameWithExtension() check
CLASS_NAME underscoresToCamelCase(String) capitalize(underscoresToCamelCase(fileNameWithoutExtension())) check

これらを設定した、OK、Applyをしてください。

注意点

ファイル名から作成するようになっています。例えば content_category.dart ファイル内で、freezed と入力して補完すると以下のようなコードになります。

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

@freezed
abstract class ContentCategory with _$ContentCategory {
  const factory ContentCategory({
    @required int id,
    @JsonKey(name: 'image_url') @required String imageUrl,
  }) = _ContentCategory;

 factory ContentCategory.fromJson(Map<String, dynamic> json) => _$ContentCategoryFromJson(json);
}

あとは、build_runner をつかってコードを生成します。詳しくは freezed をREADMEを御覧ください。

9
8
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
9
8