I'm playing with riverpod in flutter, and I got this example
AsyncError(:final error) => Text('Error: $error'),
It works, but I'm trying to understand what does :final error
mean? If I remove the :
it throws an error Object patterns can only use named fields.
Can you please provide a better example when is required to use it?
Trying to understand a certain syntax in Dart language
This is the ability to destructure a class instance field. To use the fields of an object at the time of destructuring, you can use the syntax Object(:[type] field)
(conditionally). Here are more examples:
AsyncValue? value;
final result = switch (value) {
AsyncError(:final error) => '$error',
AsyncError(:var error, :StackTrace stackTrace) => '$error $stackTrace',
AsyncError(:var error, stackTrace: StackTrace st) => '$error $st',
AsyncError<int>(:final int value) => '$value',
AsyncError(:Object error) => '$error',
AsyncValue<int>(hasValue: true) => 'hasValue is true',
AsyncValue<int>(:var hasValue) when hasValue == false => '$hasValue',
_ => 'default',
The example itself doesn't make sense here, I only showed the syntax of field extraction. Specify :
(or just inside the object's parentheses) and use the IDE prompts to see the fields available for destructuring.
Use a custom field when destructuring if necessary (as with stackTrace: StackTrace st
).
You can also immediately start mapping fields to value, as in the AsyncValue.hasValue
example. Use the when
syntax if you need this field later.
There is a very large syntax, I recommend viewing the information using the links below: