Flutter & Dart Enumeration Example

Flutter & Dart: Enumeration Example

This article will show you how to use enums (also known as enums or enum types) in Dart and Flutter.

Overview

An enumeration in Dart is a set of symbolic names (members) bound to a unique constant value. In an enumeration, members can be compared by identity, and the enumeration itself can be iterated over.

An enumeration can be declared using the enum keyword:

enum Aniaml {dog, cat, chicken, dragon}

Each value of the enumeration has an index. The index of the first value is 0.

You can retrieve all values ​​of an enumeration using the values ​​constant:

print(Aniaml.values);
// [Aniaml.dog, Aniaml.cat, Aniaml.chicken, Aniaml.dragon]

a complete example

coding:

// Declare enum
enum Gender {
  Male,
  Female
}// Make a class
class Person {
  final String name;
  final int age;
  final Gender gender;
  
  Person(this.name, this.age, this.gender); 
}// Create an instance
final personA = Person("John Doe", 40, Gender.Male);void main(){
  if(personA.gender == Gender.Male){
    print("Hello gentleman!");
  } else {
    print("Hello lady!");
  }
}

output:

Hello gentleman!

Flutter & Dart: Check if a date is between two other dates

To check if a date is between two other dates in Flutter and Dart, you can use the isBefore( ) and isAfter() methods of the DateTime class .

example

import 'package:flutter/foundation.dart';
​
DateTime dateA = DateTime(1900, 9, 14);
DateTime dateB = DateTime(2000, 10, 15);
​
DateTime dateC = DateTime(1984, 12, 20);
DateTime dateD = DateTime.now();void main() {
  if (dateA.isBefore(dateC) && dateB.isAfter(dateC)) {
    debugPrint("dateC is between dateA and dateB");
  } else {
    debugPrint("dateC isn't between dateA and dateC");
  }if (dateA.isBefore(dateD) && dateB.isAfter(dateD)) {
    debugPrint("dateD is between dateA and dateB");
  } else {
    debugPrint("dateD isn't between dateA and dateC");
  }
}

output:

dateC is between dateA and dateB
dateD isn't between dateA and dateC

You can find more information about DateTime class in the official documentation.

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *