Home > Enterprise >  Overcoming 'field_initializer_not_assignable' error
Overcoming 'field_initializer_not_assignable' error

Time:08-07

I've created a model class and am having trouble with the error: 'field_initializer_not_assignable'

Solutions I've come up with:

  1. use 'ignore_for_file:...'. This solutions works, but I don't like it. (For context, Flutter's default lints do not produce this error, but I'm using VGV's very_good_analysis so I am getting the error.)
  2. type cast the value. This solutions also works, but it then produces the following warning in the debug console: Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
    This is only a warning (the program compiles and runs), but again, I don't like it.

What is a more elegant solution? I have a feeling it's easy but can't see it.

class Product {
  Product({
    required this.name,
    required this.description,
  });

  Product.fromMap(Map<String, dynamic> map)
  // Without type cast I get the error
      : name = map['name'] ?? '',
  // A type cast workaround removes error but generates the warning
        description = map['description'] as String ?? '';

  final String name;
  final String description;...

CodePudding user response:

I think your concern is here

description = map['description'] as String

Once you use as String means it will not receive nullable string and therefore the right part of it never happen.

If you like to accept nullable and provide default value, you can use as String?, Also you've already done name = map['name'] ?? '',

 description = map['description'] as String? ?? ''
  • Related