简体   繁体   中英

Passing a Function to an annotation in dart

I want to send a Function as a parameter to an annotation like this:

@JsonKey(fromJson: ...)
final int variable;

where fromJson is a Function , but it gives me this error:

Arguments of a constant creation must be constant expressions.

what is the solution? any help would be greatly appreciated.

You didn't write what you wanted for ... , and that's the part that causes the problem.

The argument to the fromJson parameter must be a compile-time constant value because annotations must be constant.

The only constant function values are top-level or static functions, so you need to declare the function type want, let's say as static:

class MyClass {
  @JsonKey(fromJson: _variableFromJson)
  final int variable;
  
  static int _variableFromjson(dynamic json) => ...;
 
  ...
}

You can't write the function in-line as (fromJson: (json) =>...) because function expressions are not compile-time constant.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM