Flutter Enum — How to exchange values with your Backend and/or your app UI since Dart 2.6 thanks to extensions


If you are developing an application you will probably use not one, not two but many enums in your code. Even though creating a class is always possible, nothing beats the simplicity of declaring a simple enum.

Domain Layer: enum declaration

Let’s imagine we want to create an enum to describe the sports practiced by an athlete. For the sake of simplicity we will have only two values in this example, plus a default “UNKNOWN” value. As we will later understand this is important to ensure integrity with our remote database solution.

enum Sport{
  • Store and retrieve the value from a remote database without being index dependent on the enum inner indexation.

Presentation Layer: Convert enums to complex types for your UI

Since Dart 2.6, we can use extensions to add methods to our classes, including enums ! That makes it incredibly easy to add some conversions and even effectuate complex transformations.

text: Text(sport.toValue(context)),
image: sport.toImage(),

Data layer: Exchange enums with a remote database

When storing the value to a database on our server, we have two different approach. The most straightforward approach which results in the fastest implementation client side is to store the “description” of the value as a string. This also improve readability and speed up debugging.

import 'package:flutter/foundation.dart';
sport = "VOLLEYBALL";
toEnumValue(sport, values: Sport.values);
toEnumValueList(sportList, values: Sport.values);

An alternative, sometimes more efficient, approach (discouraged for most applications for which small differences in overhead and storage are not a problem).

The above solution works fine and storing the enum as String is the way to go most of the times. However, there is a more efficient solution in order to save up storage space and reduce overhead bandwidth consumption. This could be a subject in some specific applications such as TimeSeries data that would needs to store billions of lines or M2M communications that use very slow, low power, networks. In general the solution would be to just use short String that would fit in one byte as integers does, however if you have longer String, saving up 1 byte per request may still count…

Sport sport = "VOLLEYBALL";
int code = 1;
List<Sport> sportList = ["VOLLEYBALL","BEACHVOLLEY"];
List<int> codeList = [1,2];

Thanks !!

I hope this will help you in your app developments and let you save some time!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store