flutterfirebasedart

How to convert a String to an Enum in Dart?


I get a snapshot from Firestore like this:

return userCollection
    .doc(uid)
    .collection('values')
    .where(
      "created",
      isGreaterThanOrEqualTo: fromDate,
      isLessThan: toDate,
    )
    .orderBy('created', descending: true)
    .snapshots()
    .map((list) =>
        list.docs.map((doc) => Values.fromSnapshot(doc)).toList());

then I convert it to a Values Model:

  Values.fromSnapshot(DocumentSnapshot<Map<String, dynamic>> snapshot)
      : created = snapshot.data()!['created'],
        type = snapshot.data()!['type'],
        value = snapshot.data()!['value'].toDouble();

The "type" is a String. How can I convert it to a specific ValuesType Enum?

enum ValueType { first, second, third }

The String has not the same name: For example "one", "two", "three". How is the right way to do this?


Solution

  • You could change your enum to this for example

    enum ValueType {
      first,
      second,
      third;
    
      static ValueType fromString(String s) => switch (s) {
            "one" => first,
            "two" => second,
            "three" => third,
            _ => first
          };
    }
    

    And then use it as

        type = ValueType.fromString(snapshot.data()!['type']),