Properties
In most programming languages, data can be stored in variables that are either global or passed to objects in object-oriented languages. Each piece of data is stored in a class or constant variable. To enable this functionality, the API provides the PropertySpec structure. At first glance, the naming might seem unconventional, as it does not directly suggest "class variable" or reflect typical class structure terminology. However, this naming is derived from Dart's language definition. In Dart, a property is a class member variable that can be passed via a constructor, but it can also be a getter or setter property. The type of property you use depends on your specific context, as properties can have different combinations of keywords that modify their behavior.
Creating a PropertySpec generally requires two parameters: the variable name and its type. Any object can be passed as the type. The API provides a system that maps classes to a TypeName structure, which is used to represent them. Additionally, modifiers can be applied to the builder if needed. This can be done either during the builder's creation or through additional methods within the builder itself. By default, the API creates null-safe properties, meaning the property cannot be initialized with a null value. If you need a nullable property, you must specify a TypeName using the nullable() method from the builder
Not all modifiers can be applied to a Property. If you pass invalid modifiers, an error will occur.
Lets create an basic parameter without any advanced characteristics:
val property = PropertySpec.builder("name", String::class)
.initializer("%C;", "test")
.build()String name = 'test';Constant Property:
Dart also supports the concept of constant properties, which cannot be changed at runtime. To create such constant properties, you have two options: either pass the correct modifier to the builder or use the dedicated constBuilder method. The API provides special handling for constant properties. Although it is possible to omit specifying a type for constants, this is generally not recommended. While Dart’s runtime can infer the type, during development, you will only see dynamic as the type, which can lead to less clarity.
Now, let's create a simple constant property:
ConstantPropertySpec.classConst("maxId").initWith("%L", "100").build()static const maxId = 100;Last updated