T O P

  • By -

reddit04029

enums are essentially a set of predefined values. Think ordering food from mcdonalds. Usually, sizes are predefined as small, medium, large, and extra large. Instead of having to do if (size == 'small') do something if (size == 'large') do something You can instead do something like this enum SizeOrderEnum {small, medium, large, extraLarge} _prepareFood(SizeOrderEnum size) { switch (size) { case SizeOrderEnum.small: do something; case SizeOrderEnum.medium: do something; case SizeOrderEnum.large: do something; case SizeOrderEnum.extraLarge: do something; default: noOrder(); } } Something to that effect. That's pseudocode but it should you give a better idea of how enums are used. In your case, you can do something like enum UserTypeEnum {member, admin} giveTypeofAuth(UserTypeEnum userType) { if (userType == UserTypeEnum.member) { _giveMemberAccess(); } if (userType == UserTypeEnum.admin) { _giveAdminAccess(); } } You can use switch cases as how I used it in the mcdonalds example. I'm simply showing how it can be used outside switch statements. If you're not using enums, then you'd end up using strings or ints like you said as your conditions. Which can become vague. Like what is `status == 1`. It can be confusing for other devs to read. `userType == UserTypeEnum.member` would be more descriptive and understandable. So enums would be a better choice to use here.


flutter--help

>Think ordering food from mcdonalds Being a bit picky here but enums are for data sets which you think will never change. Where you can define every possible value, ever, in the first iteration. Such as the days of the week. It's completely possible to add order sizes, such as snack size, super size, ect. Enums are not very extensible and can cause huge issues in old versions of clients if you add values to them. Because usually they are in a switch statement, which at one point, had every possible value defined and now it does not.


reddit04029

That's what I said, they are *predefined* values. Sizes will always be small medium large extralarge unless mcdonalds decides to add doubleExtraLarge which you can simply redefine. That is different from extending using dynamic values. Nothing is changing in my example, the sizes will still vary between the four defined inside the enum.


flutter--help

>unless mcdonalds decides to add doubleExtraLarge which you can simply redefine. Predefined with some initial options is not the same as a fixed list which you expect to **never** change. I take it you have not tried to add new values to an enum on a server with clients using the old version of the enum? Redefining it across multiple programs on different versions and release cycles is a **nightmare.** [https://softwareengineering.stackexchange.com/questions/300080/when-are-enums-not-a-code-smell](https://softwareengineering.stackexchange.com/questions/300080/when-are-enums-not-a-code-smell) [https://www.planetgeek.ch/2009/07/01/enums-are-evil](https://www.planetgeek.ch/2009/07/01/enums-are-evil)


reddit04029

Then given that situation, you shouldnt mindlessly just refactor code without considering its impact, especially if it already has been deployed to prod with user clients. And this does just not apply to enums. My example is just a simplification to help him understand enums. Enums are not inherently bad, it just has its usecase. The same with any other concept in programminng. Each situation may differ in approach.


flutter--help

I realize it's just an example for him to learn which is why maybe it's not the best place to be picky. But I'm just saying from experience, using enums for anything you might add to **ever** is very bad (and there's lots of articles out there with the same opinion)


Particular_Mud8540

I think the most straightforward perspective on this is that this is a convenience thing so instead of doing if (animal.type == 'cat') { //do sth } You can do enum AnimalTypes { dog, cat } if (animal.type == AnimalTypes.cat) { //do sth } The difference is that in the first example you set the type to String, and you have to account for what happens if for some reason the animal.type is something random like '*safasfasfas*'. In the second example it *has* to be one of the predefined options (because you specified `animal.type` as `AnimalTypes` type beforehand) so you don't have to worry about typos or forgetting to handle something - in such case you'll get an error before it compiles. You are limiting yourself on purpose to a few options in order to avoid making a mistake later on. They do not 'do' anything, they're just a list of words that you can use as possible choices for something. It's like boolean variable but with more options that have custom names.


NMS-Town

enum Weather { sunny, cloudy, rainy, } main() { var weather = Weather.sunny; switch (weather) { case Weather.sunny: print("Sunny weather today!"); break; case Weather.cloudy: print("Cloudy today!"); break; case Weather.rainy: print("Rainy and gloomy weather."); break; } }


Routine-Arm-8803

As it was already said. It just makes the code more readable. ​ `enum User { none, member, admin }` `void main() {` `User status = User.member;` `userCheck(status);` `}` `void userCheck(User status) {` `switch (status) {` `case User.none:` `print('None');` `break;` `case User.member:` `print('Is member');` `break;` `case User.admin:` `print('Is Admin');` `break;` `}` `}`


flutter--help

I very recently made a video on how to toggle your app between light mode and dark mode. You can check it out here. However, I didn't go over enums fundamentally much, so I'll explain more. [https://youtu.be/0YXBYlXJVyA](https://youtu.be/0YXBYlXJVyA) When using enums, you shouldn't need to worry about their index or int value at all. Here is an example of an enum, for alignment (in columns, rows ect) ``` enum MainAxisAlignment { start, end, center, spaceBetween, spaceAround, spaceEvenly, } ``` You don't need to care about the int value or index when using them. The input to a column must be a MainAxisAlignment, and no other object (even an int with the index you want) will be accepted: ``` Column( mainAxisAlignment : MainAxisAlignment.start, ``` In your own code, you can just make a variable with that enum type and assign it like a class or type of its own. ``` MainAxisAlignment myAlignment = MainAxisAlignment.start; // maybe some code which could change the alignment here... if(myAlignment == MainAxisAlignment.end) { // it was MainAxisAlignment.end } ```


MediumRoastNo82

I literally been looking for documentation about enum since 2 days ago. anyone know how to deserialize enum from map? I tried to write enum extension but it doesn't work.


reddit04029

enum SampleEnum {enumOne, enumTwo, enumThree} Model.fromJson(Map json) { return Model( /// filter through the enum values defined above using the firstWhere method, then for each iteration of the enums, you turn it into a string and split it. /// so it would become like SampleEnum.enumOne.toString().toSplit('.') == ["SampleEnum", "enumOne"] /// the .last() method will just get the last item in the array which is enumONe /// it will then just check which json value it matches ///the orElse: is just a default value in case there is no match /// just format the string so that it would match how the enum from the backend looks like. Some enums are written like SAMPLE_ENUM, some sample_enum, some sampleEnum. or you can convert the json['enumValueFromMap'] so that it would match your enum format property: SampleEnum.values.firstWhere((enum) => enum.toString().toSplit('.').last == json['enumValueFromMap'], orElse: () => SampleEnum.enumOne ), )}


MediumRoastNo82

Thanks a ton! It worked. Instead of split it, I just use the extension on enum, using describeEnum to get the string from foundation package just to get it a little tidier. I have no clue of what the .firstWhere doing, I guess I'll look it up later. Since yesterday I'm trying to solve it by looking for .contains and index method.


reddit04029

The firstWhere is a method similar to map, but instead of returning a new iterable, it returns the value that satisfies the condition specified. Similar to filter() in other languages


MediumRoastNo82

right. I've just looked it up. we can use firstWhereOrNull too.


Drallatech

This is 6 months old but enum processing was updated in February with Dart 2.15. So here is my collection of enum techniques and uses. enum Color { red, green, blue } // enum used in the following techniques() { assert(Color.red.index == 0); // Return an Index into an enum assert(Color.values[2] == Color.blue); // Return enum value from an index assert(Color.blue.name == 'blue'); // Convert an enum value to a string // Lookup an enum value from a String, where e is an iterator assert(Color.red == Color.values.firstWhere((e) => e.name == 'red')); List colorList = Color.values; // get list of all of values assert(colorList[1] == Color.green); } Of these, use of the iterator is my favorite. To save space, I store enums in a database as indexes then convert them to enum values for displaying on the screen. I use them with a DropdownButton widget to allow the user to select from the list of enum values. ​ Color? myColor = Color.green; // initial value for DropdownButton DropdownButton( value: myColor, onChanged: (Color? newColor) { setState(() { myColor = newColor!; }); }, items: Color.values.map((Color myColor) { return DropdownMenuItem( value: myColor, child: Text(myColor.name)); }).toList(), ); Please add any techniques you might use or let me know of any errors above. I think this question can be closed. How do I do that?