Flutter Tutorials

How to Create Enum in Flutter?

· · Updated March 23, 2024
How to create enum in flutter

In this article, we’ll explore how to create enum in Flutter, accompanied by code examples and various use cases.

Enums, short for enumerations, are a powerful tool in programming languages to define a set of named values.

You can follow the official documentation to set up Flutter: Flutter Installation Guide.

Flutter, the UI toolkit from Google, also supports enums, providing a clean and structured way to represent a fixed set of values.

Table of Contents

What is an Enum?

An enumeration, often referred to as an “enum,” is a special data type in Flutter that allows you to define a group of related constants or named values. These constants, also known as enumerators, represent a finite set of distinct values.

Enums provide a way to organize and structure your code by assigning meaningful names to specific values, making your code more readable and maintainable.

How to create enum in Flutter?

To create an enum in Flutter, use the enum keyword followed by the enum’s name. Let’s consider a simple example of defining an enum for days of the week:

enum DaysOfWeek {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}

In this example, DaysOfWeek is the enum name, and it contains seven enumerators, each representing a day of the week.

Also Read: Draw horizontal line in a flutter

Use of create enum in Flutter

Switch Statements

One common use of enums is in switch statements, making code more readable and maintainable. Let’s say you want to perform different actions based on the day of the week:

String getDayMessage(DaysOfWeek day) {
  switch (day) {
    case DaysOfWeek.Monday:
      return 'Start of the week!';
    case DaysOfWeek.Friday:
      return 'TGIF!';
    // Handle other days accordingly
    default:
      return 'Enjoy your day!';
  }
}

Enums are often used to populate dropdown menus in Flutter, providing a predefined set of options. Consider the following example of a dropdown menu for selecting a day of the week:

DropdownButton<DaysOfWeek>(
  value: selectedDay,
  onChanged: (DaysOfWeek newValue) {
    setState(() {
      selectedDay = newValue;
    });
  },
  items: DaysOfWeek.values.map((DaysOfWeek day) {
    return DropdownMenuItem<DaysOfWeek>(
      value: day,
      child: Text(day.toString().split('.').last),
    );
  }).toList(),
)

Indexed Access

You can access the index of an enum value, which is particularly useful when you need to work with numerical representations:

dartCopy code

int dayIndex = DaysOfWeek.Friday.index; // Returns 4

Iterating Over Enums

To iterate over all values of an enum, use the values property:

for (var day in DaysOfWeek.values) {
  print(day);
}

Full Code:

import 'package:flutter/material.dart';

// Define the enum for days of the week
enum DaysOfWeek {
  Monday,
  Tuesday,
  Wednesday,
  Thursday,
  Friday,
  Saturday,
  Sunday,
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Enum Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // Example 1: Switch Statements
              Text(getDayMessage(DaysOfWeek.Monday)),

              // Example 2: Dropdown Menu
             DropdownButton<DaysOfWeek>(
  value: DaysOfWeek.Monday,
  onChanged: (DaysOfWeek? newValue) {
    // Handle dropdown selection
//     print('Selected day: $newValue');
  },
  items: DaysOfWeek.values.map((DaysOfWeek day) {
    return DropdownMenuItem<DaysOfWeek>(
      value: day,
      child: Text(day.toString().split('.').last),
    );
  }).toList(),
),

              // Example 3: Indexed Access
              Text('Index of Friday: ${DaysOfWeek.Friday.index}'),

              // Example 4: Iterating Over Enums
              ElevatedButton(
                onPressed: () {
                  iterateOverEnums();
                },
                child: Text('Iterate Over Enums'),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // Example 1: Switch Statements
  String getDayMessage(DaysOfWeek day) {
    switch (day) {
      case DaysOfWeek.Monday:
        return 'Start of the week!';
      case DaysOfWeek.Friday:
        return 'TGIF!';
      // Handle other days accordingly
      default:
        return 'Enjoy your day!';
    }
  }

  // Example 4: Iterating Over Enums
  void iterateOverEnums() {
    for (var day in DaysOfWeek.values) {
      print(day);
    }
  }
}

Output:

Conclusion

Enums in Flutter offer a structured way to represent a fixed set of values, enhancing code readability and maintainability. Whether you’re using them in switch statements, dropdown menus, or other scenarios, enums can make your Flutter development experience more enjoyable.

Ambika Dulal

About Ambika Dulal

Lead Mobile App Developer and Tech Consultant specializing in Flutter, Dart, and Firebase.