Dart How to get the “value” of an enum

后端 未结 15 2084
野的像风
野的像风 2020-12-29 00:50

Before enums were available in Dart I wrote some cumbersome and hard to maintain code to simulate enums and now want to simplify it. I need to get the value of the enum as

15条回答
  •  余生分开走
    2020-12-29 01:13

    I had the same problem in one of my projects and existing solutions were not very clean and it didn't support advanced features like json serialization/deserialization.

    Flutter natively doesn't currently support enum with values, however, I managed to develop a helper package Vnum using class and reflectors implementation to overcome this issue.

    Address to the repository:

    https://github.com/AmirKamali/Flutter_Vnum

    To answer your problem using Vnum, you could implement your code as below:

    @VnumDefinition
    class Visibility extends Vnum {
      static const VISIBLE = const Visibility.define("VISIBLE");
      static const COLLAPSED = const Visibility.define("COLLAPSED");
      static const HIDDEN = const Visibility.define("HIDDEN");
    
      const Visibility.define(String fromValue) : super.define(fromValue);
      factory Visibility(String value) => Vnum.fromValue(value,Visibility);
    }
    

    You can use it like :

    var visibility = Visibility('COLLAPSED');
    print(visibility.value);
    

    There's more documentation in the github repo, hope it helps you out.

提交回复
热议问题