From Kotlin to Dart 2 Cheat Sheet - Classes

Constructor Call

Kotlin

val file = File("file.txt")

Dart

final config = File('file.txt');

Simple class

Kotlin

class Post

Dart

class Post {

}

Primary Constructor

Kotlin

class User constructor(id: String) {
    var id: String = id
}

Dart

class User {
  String id;

  User(String id) {
    this.id = id;
  }
}

Final Properties

Kotlin

class User(val id: String)

Dart

class User {
  final String id;

  User(this.id);
}

Optional Arguments in Constructors

Kotlin

fun main() {
    val user1 = User("some_id")
    val user2 = User("some_id", 25)

    println(user1.age) // prints '18'
    println(user2.age) // prints '25'
}

data class User(val id: String, val age: Int = 18)

Dart

main(List<String> arguments) {
  final user1 = User(id: "some_id");
  final user2 = User(id: "some_id", age: 25);

  print('${user1.age}'); // prints '18'
  print('${user2.age}'); // prints '25'
}

class User {
  final String id;

  final int age;

  const User({this.id, this.age = 18});
}

Read-Only Properties

Kotlin

class Rectangle(private val width: Int, private val height: Int) {
    val area: Int = width * height
}

Dart

class Rectangle {
  int _height;
  int _width;

  Rectangle(this._width, this._height);

  int get area => _width * _height;
}

Abstract Class

Kotlin

abstract class Removable {
    abstract fun remove()
}

Dart

abstract class Removable {
  void remove();
}

Interface

Kotlin

interface Removable {
    fun remove()
}

class Post : Removable {
    override fun remove() {
        // TODO: implement remove
    }
}

Dart

abstract class Removable {
  void remove();
}

class Post implements Removable {
  @override
  void remove() {
    // TODO: implement remove
  }
}

Get Discounted Courses from Udemy:

Udemy

Share on: