Chapter 4. Control Flow - Enum values and indexes

Hi @suragch,

Further to a previous conversation about “But why???”, here is an example.

In Chapter 4. Control Flow, the section “Enum values and indexes” is presented to the reader, but with very little context.

Sure, we can get the index, but why would we need to, or want to?



One reason someone might want to convert an enum to an int is to save the value somewhere. It often isn’t possible to directly save an enum to storage. But you can save an int and then later convert the int back to an enum. Note that you need to be careful, though, because if you ever save an int value from an enum and then change the order of the items in the enum, you’ll get unexpected results when you try to convert the saved int back to the new enum.

Another application is looping over the values of an enum. See this for more: flutter - How to loop over an enum in Dart - Stack Overflow

I’ll look at answering the “But why?” question in the next book update. Thanks for asking.

This content is included in the upcoming publication Dart Apprentice: Fundamentals chapter 5, “Control Flow”.

1 Like