Skip to content

Commit cfb7937

Browse files
committed
Fix enum value retrieval
1 parent 88a0693 commit cfb7937

File tree

1 file changed

+9
-15
lines changed

1 file changed

+9
-15
lines changed

openapi-generator/lib/src/extensions/type_methods.dart

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import 'dart:mirrors';
22

33
import 'package:analyzer/dart/element/type.dart';
4-
import 'package:source_gen/source_gen.dart' show ConstantReader;
4+
import 'package:source_gen/source_gen.dart' show ConstantReader, TypeChecker;
55

66
/// Extension adding the type methods to `ConstantReader`.
77
extension TypeMethods on ConstantReader {
@@ -54,26 +54,20 @@ extension TypeMethods on ConstantReader {
5454
}
5555

5656
final classMirror = reflectClass(T);
57-
final typeMirror = reflectType(T);
5857
if (!classMirror.isEnum) {
5958
throw Exception(
6059
'Could not read constant via enumValue<$T>(). $T is not a Dart enum.');
6160
}
62-
final varMirrors = <VariableMirror>[];
63-
for (final item in classMirror.declarations.values) {
64-
if (item is VariableMirror && item.type == typeMirror) {
65-
varMirrors.add(item);
66-
}
61+
62+
if (!instanceOf(TypeChecker.fromRuntime(T))) {
63+
throw Exception('Not an instance of $T.');
6764
}
65+
6866
// Access enum field 'values'.
6967
final values = classMirror.getField(const Symbol('values')).reflectee;
70-
for (final varMirror in varMirrors) {
71-
final name = MirrorSystem.getName(varMirror.simpleName);
72-
final index = peek(name)?.intValue;
73-
if (index != null) {
74-
return values[index];
75-
}
76-
}
77-
throw Exception('Could not read enum instance of type $T.');
68+
// Get enum field 'index'.
69+
final enumIndex = objectValue.getField('index')!.toIntValue();
70+
71+
return values[enumIndex];
7872
}
7973
}

0 commit comments

Comments
 (0)