Belajar Bahasa Pemrograman Dart : Enumerated Types

Dhe997

Enumerated Types

Bagaimana kita bisa menyimpan banyak nilai konstan di satu tempat dan menanganinya secara bersamaan? 

Solusinya, Dart menyediakan EnumsEnum mewakili kumpulan konstan yang membuat kode kita lebih jelas dan mudah dibaca.


  1. enum Rainbow {

  2.   red, orange, yellow, green, blue, indigo, violet

  3. }

  4.  

  5. enum Status {

  6.   Todo, In_Progress, In_Review, Done

  7. }





Enum pada Dart memiliki beberapa property bawaan yang dapat kita gunakan untuk menampilkan seluruh nilai dalam bentuk list serta menampilkan item dan indeks dari item tersebut.


  1. print(Rainbow.values);

  2. print(Rainbow.blue);

  3. print(Rainbow.orange.index);





Ketika kode di atas dijalankan, maka konsol akan tampil seperti berikut:


  1. [Rainbow.red, Rainbow.orange, Rainbow.yellow, Rainbow.green, Rainbow.blue, Rainbow.indigo, Rainbow.violet]

  2. Rainbow.blue

  3. 1



Kita juga bisa menggunakan enum ke dalam switch statements. Namun kita perlu menangani semua kemungkinan nilai enum yang Ada.


  1. var taskStatus = Status.In_Progress;

  2.  

  3. switch(taskStatus) {

  4.   case Status.Todo:

  5.     print('Task is still in To do');

  6.     break;

  7.   case Status.In_Progress:

  8.     print('Task is in progress');

  9.     break;

  10.   case Status.In_Review:

  11.     print('Task is currently under review');

  12.     break;

  13.   case Status.Done:

  14.     print('Task is done');

  15.     break;

  16. }


Posting Komentar

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.