2020/8/27 Dart : tour>>classes>>Methods〜の訳




Using class members


Using constructors


Getting an object’s type


Instance variables





Methods are functions that provide behavior for an object.


Instance methods

Instance methods on objects can access instance variables and this. The distanceTo() method in the following sample is an example of an instance method:


import 'dart:math';

class Point {
  double x, y;

  Point(this.x, this.y);

  double distanceTo(Point other) {
    var dx = x - other.x;
    var dy = y - other.y;
    return sqrt(dx * dx + dy * dy);


Operators are instance methods with special names. Dart allows you to define operators with the following names:


< + | >>>
> / ^ []
<= ~/ & []=
>= * << ~
- % >> ==

Note: You may have noticed that some operators, like !=, aren’t in the list of names. That’s because they’re just syntactic sugar. For example, the expression e1 != e2 is syntactic sugar for !(e1 == e2).

注意 : != などのいくつかの演算子が上記の表に記載されていません。なぜならそれらの表現は糖衣構文だからです。例えば、e1 != e2という表現は、!(e1 == e2)の糖衣構文です。


An operator declaration is identified using the built-in identifier operator. The following example defines vector addition (+) and subtraction (-):


class Vector {
  final int x, y;

  Vector(this.x, this.y);

  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);

  // Operator == and hashCode not shown.
  // ···

void main() {
  final v = Vector(2, 3);
  final w = Vector(2, 2);

  assert(v + w == Vector(4, 5));
  assert(v - w == Vector(0, 1));


Getters and setters

Getters and setters are special methods that provide read and write access to an object’s properties.



Recall that each instance variable has an implicit getter, plus a setter if appropriate.



You can create additional properties by implementing getters and setters, using the get and set keywords:


class Rectangle {
  double left, top, width, height;

  Rectangle(this.left, this.top, this.width, this.height);

  // Define two calculated properties: right and bottom.
  // rightとbottom : 二つのcalculated propertiesを定義する。
  double get right => left + width;
  set right(double value) => left = value - width;
  double get bottom => top + height;
  set bottom(double value) => top = value - height;

void main() {
  var rect = Rectangle(3, 4, 20, 15);
  assert(rect.left == 3);
  rect.right = 12;
  assert(rect.left == -8);

With getters and setters, you can start with instance variables, later wrapping them with methods, all without changing client code.



Note: Operators such as increment (++) work in the expected way, whether or not a getter is explicitly defined. To avoid any unexpected side effects, the operator calls the getter exactly once, saving its value in a temporary variable.

注意:increment (++)のような演算子は、ゲッターが明示的に定義されているかどうかに関わらず、期待される方法で動作します。予期せぬ副作用を避けるために、演算子はゲッターを一度だけ呼び、その値を一時変数に保存します。


Abstract methods

Instance, getter, and setter methods can be abstract, defining an interface but leaving its implementation up to other classes. Abstract methods can only exist in abstract classes.



To make a method abstract, use a semicolon (;) instead of a method body:


abstract class Doer {
  // Define instance variables and methods...
  // インスタンスフィールドとメソッドの定義...

  void doSomething(); // Define an abstract method.

class EffectiveDoer extends Doer {
  void doSomething() {
    // Provide an implementation, so the method is not abstract here...
    // 継承先で抽象メソッドの実装を記述する。


Abstract classes

Use the abstract modifier to define an abstract class



a class that can’t be instantiated.



Abstract classes are useful for defining interfaces, often with some implementation.



If you want your abstract class to appear to be instantiable, define a factory constructor.



Abstract classes often have abstract methods. Here’s an example of declaring an abstract class that has an abstract method:


abstract class AbstractContainer {
  // Define constructors, fields, methods...

  void updateChildren(); // ←抽象メソッド


Implicit interfaces

Every class implicitly defines an interface containing all the instance members of the class and of any interfaces it implements.



If you want to create a class A that supports class B’s API without inheriting B’s implementation, class A should implement the B interface.



A class implements one or more interfaces by declaring them in an implements clause and then providing the APIs required by the interfaces. For example:

クラスは、1つまたは複数のインターフェースをimplementsキーワードで宣言し、 インターフェースが必要とするAPIを提供(実装)することによって、インターフェースを実装します。例えば

// A person. The implicit interface contains greet().
class Person {
  // In the interface, but visible only in this library.
  final String _name;

  // Not in the interface, since this is a constructor.

  // In the interface.
  String greet(String who) => 'Hello, $who. I am $_name.';

// An implementation of the Person interface.
class Impostor implements Person {
  String get _name => '';

  String greet(String who) => 'Hi $who. Do you know who I am?';

String greetBob(Person person) => person.greet('Bob');

void main() {


Here’s an example of specifying that a class implements multiple interfaces:


class Point implements Comparable, Location {...}


Extending a class

Use extends to create a subclass, and super to refer to the superclass:


class Television {
  void turnOn() {
  // ···

class SmartTelevision extends Television {
  void turnOn() {
  // ···

For another usage of extends, see the discussion of parameterized types in generics.

extendsの他の使い方については、genericsのparameterized typesをご覧ください。

Overriding members

Subclasses can override instance methods (including operators), getters, and setters.



You can use the @overrideannotation to indicate that you are intentionally overriding a member:


class Television {
  // ···
  set contrast(int value) {...}

class SmartTelevision extends Television {
  set contrast(num value) {...}
  // ···

An overriding method declaration must match the method (or methods) that it overrides in several ways:



  • The return type must be the same type as (or a subtype of) the overridden method’s return type.



  • Argument types must be the same type as (or a supertype of) the overridden method’s argument types. In the preceding example, the contrast setter of SmartTelevision changes the argument type from int to a supertype, num.




  • If the overridden method accepts n positional parameters, then the overriding method must also accept n positional parameters.



  • A generic method can’t override a non-generic one, and a non-generic method can’t override a generic one.



Sometimes you might want to narrow the type of a method parameter or an instance variable.



This violates the normal rules, and it’s similar to a downcast in that it can cause a type error at runtime.



Still, narrowing the type is possible if the code can guarantee that a type error won’t occur.



In this case, you can use the covariant keyword in a parameter declaration. For details, see the Dart language specification.

この場合は、引数の宣言にcovariantキーワードを使います。詳しくはDart language specificationをご覧ください。


Warning: If you override ==, you should also override Object’s hashCode getter. For an example of overriding ==and hashCode, see Implementing map keys.

==演算子をオーバーライドする場合、オブジェクトのhashCodeゲッターも一緒にオーバーライドすべきです。==とhashCodeのオーバーライドの具体例は、Implementing map keysをご覧ください。




Extension methods

Extension methods are a way to add functionality to existing libraries.

Extension methodsは既存のライブラリに機能を追加する方法です。


You might use extension methods without even knowing it.

あなたは気づかずにextension methodを使っている可能性があります。


For example, when you use code completion in an IDE, it suggests extension methods alongside regular methods.

例えば、IDEでコード補完を使うと、通常のメソッドと一緒にextension methodも提案されます。


Here’s an example of using an extension method on String named parseInt() that’s defined in string_apis.dart:

下記の例は、Stringクラスのextension methodであるparseInt()です。(string_apis.dart)

import 'string_apis.dart';
print('42'.padLeft(5)); // Use a String method.
print('42'.parseInt()); // Use an extension method.

For details of using and implementing extension methods, see the extension methods page.

さらに詳しい情報は、extension methods pageをご覧ください。

Enumerated types

Enumerated types, often called enumerations or enums, are a special kind of class used to represent a fixed number of constant values.



Note: All enums automatically extend the Enum class. They are also sealed, meaning they cannot be subclassed, implemented, mixed in, or otherwise explicitly instantiated.

注意 : 全てのenumは自動的にEnumクラスのサブクラスとなります。これらのenumはsealedなものとなります。つまり、enumをサブクラス化・実装・ミックスインすることはできません。また、enumをインスタンス化することもできません。


Abstract classes and mixins can explicitly implement or extend Enum, but unless they are then implemented by or mixed into an enum declaration, no objects can actually implement the type of that class or mixin.


Declaring simple enums

To declare a simple enumerated type, use the enum keyword and list the values you want to be enumerated:


enum Color { red, green, blue }


Tip: You can also use trailing commas when declaring an enumerated type to help prevent copy-paste errors.



Declaring enhanced enums

Dart also allows enum declarations to declare classes with fields, methods, and const constructors which are limited to a fixed number of known constant instances.



To declare an enhanced enum, follow a syntax similar to normal classes, but with a few extra requirements:

enhanced enumを宣言するには、基本的に通常のクラスの宣言方法に従いますが、いくつかの追加の要件を守る必要があります。


  • Instance variables must be final, including those added by mixins.







  • No other class can be extended as Enum is automatically extended.



  • There cannot be overrides for index, hashCode, the equality operator ==.

index , hashCode , ==演算子をオーバーライドすることはできません。


  • A member named values cannot be declared in an enum, as it would conflict with the automatically generated static values getter.



  • All instances of the enum must be declared in the beginning of the declaration, and there must be at least one instance declared.



Here is an example that declares an enhanced enum with multiple instances, instance variables, a getter, and an implemented interface:

以下は、複数のインスタンス、インスタンス変数、ゲッター、および実装されたインタフェースを持つenhanced enumを宣言する例です。

enum Vehicle implements Comparable<Vehicle> {
  car(tires: 4, passengers: 5, carbonPerKilometer: 400),//80
  bus(tires: 6, passengers: 50, carbonPerKilometer: 800),//16
  bicycle(tires: 2, passengers: 1, carbonPerKilometer: 0);//0

  const Vehicle({
    required this.tires,
    required this.passengers,
    required this.carbonPerKilometer,

  final int tires;
  final int passengers;
  final int carbonPerKilometer;

  int get carbonFootprint => (carbonPerKilometer / passengers).round();

  int compareTo(Vehicle other) => carbonFootprint - other.carbonFootprint;


Version note: Enhanced enums require a language version of at least 2.17.

Enhanced enumの使うにはDartバージョン2.17以降が必要です。

Using enums

Access the enumerated values like any other static variable:


final favoriteColor = Color.blue;
if (favoriteColor == Color.blue) {
  print('Your favorite color is blue!');


Each value in an enum has an index getter, which returns the zero-based position of the value in the enum declaration. For example, the first value has index 0, and the second value has index 1.

列挙型のそれぞれの値がindexゲッターを持っています。indexゲッターは、enumの宣言の中での宣言の順番通り0から順にポジションとして割り振られます。例えば一番最初の値がindex 0、二番目の値がindex 1です。

assert(Color.red.index == 0);
assert(Color.green.index == 1);
assert(Color.blue.index == 2);


To get a list of all the enumerated values, use the enum’s values constant.


List<Color> colors = Color.values;
assert(colors[2] == Color.blue);


You can use enums in switch statements, and you’ll get a warning if you don’t handle all of the enum’s values:


var aColor 
= Color.blue;

switch (aColor) {
  case Color.red:
    print('Red as roses!');
  case Color.green:
    print('Green as grass!');
  default: // Without this, you see a WARNING.
    print(aColor); // 'Color.blue'


If you need to access the name of an enumerated value, such as 'blue' from Color.blue, use the .nameproperty:


print(Color.blue.name); // 'blue'


Adding features to a class: mixins



Class variables and methods







メールアドレスが公開されることはありません。 が付いている欄は必須項目です