LoginSignup
3
2

More than 3 years have passed since last update.

Dartにはdata classはない

Last updated at Posted at 2020-03-29

環境

訳あって最新版を使っていません(macをCatalinaにアップデートできない==Xcodeの最新版を入れられないので)。
従って、バージョン違いによる不動作などあるかも知れません。お気づきの点があったら是非コメント下さい。

$ flutter --version
Flutter 1.12.13+hotfix.5 • channel stable • https://github.com/flutter/flutter.git
Framework • revision 27321ebbad (4 months ago) • 2019-12-10 18:15:01 -0800
Engine • revision 2994f7e1e6
Tools • Dart 2.7.0

要点

Dartには、Kotlinで便利なdata classがありません。
その結果何が起こるかというと、operator==hashCodetoStringなどを全部自分で書かないと行けないと言うことです。Java時代のあの苦労よもう一度、というわけです。

それを知らないでKotlinのノリでUnitTest書いていたら全然パスしなくてググりました(汗)

下記のパッケージを使うという手もあるようですが、ちょっと多機能すぎる気がして、私は使うのを見送りました。

ちなみに、公式に議論はされているようです。
https://github.com/dart-lang/language/issues/314

以下テンプレ作ったので良ければ使って下さい。

class ClassA{
  double valueA;
  String valueB;
  Map<String, String> map;

  @override
  bool operator ==(Object other) {
    return other is ClassA &&
        valueA == other.valueA &&
        valueB == other.valueB &&  // 文字列も`==`での比較でOK
        mapEquals(map, other.map); // Deep比較してくれる。ListにはlistEqualsがある
  }

  @override
  int get hashCode => valueA.hashCode ^ valueB.hashCode ^ map.hashCode;

  @override
  String toString() {
    return "$valueA, $valueB, $map";
  }
}

参考

Stringのoperator==をテストした時のコード

import 'package:flutter_test/flutter_test.dart';
import 'package:matcher/matcher.dart';

void main() {
 group("Stringのテスト", () {
    test('operator ==:a,b==null', () {
      String a;
      String b;
      expect(a==b, isTrue);
    });
    test('operator ==:a,b have same String', () {
      String a="abs";
      String b="abs";
      expect(a==b, isTrue);
    });
    test('operator ==:a,b are same Instance', () {
      String a="abs";
      String b=a;
      expect(a==b, isTrue);
    });
    test('operator ==:a==null', () {
      String a;
      String b="abs";
      expect(a==b, isFalse);
    });
    test('operator ==:a==null', () {
      String a="abs";
      String b;
      expect(a==b, isFalse);
    });
    test('operator ==:a,b have NOT same String', () {
      String a="abs";
      String b="abc";
      expect(a==b, isFalse);
    });
  });
}

Matcherライブラリpubspec.yamlに以下のように追記します。

pubspec.yaml
dev_dependencies:
  flutter_test:
    sdk: flutter

  # matcher
  matcher: ^0.12.6

参考サイト

Dart で簡単に data class を作りたい
https://hisaichi5518.hatenablog.jp/entry/2019/12/02/205539

3
2
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
3
2