skip to Main Content

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?

2

Answers


  1. 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']),
    
    Login or Signup to reply.
  2. I’d go for the following method:

    enum Foo {
      bar,
      baz,
    }
    
    final myEnumString = 'bar';
    final myEnumValue = Foo.values.byName(myEnumString);
    

    This won’t require any extra methods to be written or updated as enums change.

    In your case this would be:

    final type = ValueType.values.byName(snapshot.data()!['type']);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search