'The parameter 'id' can't have a value of 'null' because of its type, but the implicit default value is 'null'
I am following a Flutter tutorial that has such a following code, but code doesn't work on my computer, and I don't know how to fix it:
import 'package:flutter/foundation.dart';
class CartItem {
final String id;
CartItem({
@required this.id,
});
}
But I get such these errors:
The parameter 'id' can't have a value of 'null' because of its type, but the implicit default value is 'null'.
Try adding either an explicit non-'null' default value or the 'required' modifier.dartmissing_default_value_for_parameter
{String id}
Solution 1:[1]
You have a few options depending on your own project...
Option1: Make id nullable, you can keep @required or remove it.
class CartItem {
final String? id;
CartItem({
this.id,
});
}
Option2: Give a default (non-null) value to id
class CartItem {
final String id;
CartItem({
this.id="",
});
}
more in this link
Solution 2:[2]
The latest dart version now supports sound null safety. The tutorial must be using an old version.
To indicate that a variable might have the value null, just add ? to its type declaration:
class CartItem {
final String? id = null;
CartItem({
this.id,
});
}
or
class CartItem {
final String? id;
CartItem({
this.id,
});
}
Solution 3:[3]
You can just replace @required this.id with required this.id.
Solution 4:[4]
class City {
int id;
String name;
String imageUrl;
bool isPopular;
City(
{required this.id,
required this.name,
required this.imageUrl,
required this.isPopular});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | DanOps |
| Solution 3 | enzo |
| Solution 4 | Afid Yoga |
