I've created a model class and am having trouble with the error: 'field_initializer_not_assignable'
Solutions I've come up with:
Warning: Operand of null-aware operation '??' has type 'String' which excludes null.
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;...
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? ?? ''