Static reflection for Flutter. Similar to dart:mirrors, but uses compile time code generation.
The package will create a companion class that holds static constants representing each field in the original class.
field_key_generator_example.mov
To run the example, follow these steps:
- Run build_runner to generate the field keys:
dart run build_runner build - Run the example:
dart run bin/person.dart
To use the Field Key Generator, follow these steps:
- Import the library and add the part directive to the file where you want to generate field keys.
// person.dart
import 'package:field_key_generator/field_key_generator.dart';
part 'person.g.dart';-
Annotate your class with
@GenerateFieldKeys()to indicate that you want field keys generated for it.You can exclude specific fields by providing their names in the
excludeparameter. You can also include only specific fields by providing their names in theincludeparameter. Only one ofexcludeorincludecan be used at a time.
@GenerateFieldKeys(exclude: ['fullName'])
class Person {
final String firstName;
final String lastName;
final int age;
String get fullName => '$firstName $lastName';
Person({
required this.firstName,
required this.lastName,
required this.age,
});
}-
Run the code generation step. The generator will create a companion class (e.g.,
$PersonFieldKeys) with static constants for the annotated fields.Using the
build_runnerpackage:dart run build_runner build.The generated file will be named
person.g.dartand will look like this:
class $PersonFieldKeys {
static const String firstName = 'firstName';
static const String lastName = 'lastName';
static const String age = 'age';
}
- Now, you can use these generated constants for type-safe access to field names in your code, the risk of typos. If the field name changes, you will get a compile-time error and you can easily update the field key.
void main(List<String> arguments) {
// Use the generated field keys in a database operation
deleteDatabaseRecord(
'persons',
where: $PersonFieldKeys.firstName,
whereArgs: ['John'],
);
}