The non-nullable local variable ‘product’ must be assigned before it can be used.
Try giving it an initializer expression, or ensure that it’s assigned on every execution path.
But the way I thought it ends up giving error
//product_model_test.dart
import 'package:flutter_test/flutter_test.dart';
import 'package:app/models/product/product_model.dart';
void main() {
testWidgets('Test id', (tester) async {
ProductModel product;
print(product.id); //gives this error in product - The non-nullable local variable 'product' must be assigned before it can be used. Try giving it an initializer expression, or ensure that it's assigned on every execution path.
});
}
//product_model.dart
class ProductModel{
ProductModel.fromWeb(Map data) {
id = data['id'];
description= data['description'];
icon= data['icon'];
}
late final int id;
late final String description;
late final String? icon;
}
2
Answers
In this way the error was solved
You should assign a value for
ProductModel product
before using it.Like:
If you want to tell dart that the variable hasn’t been initialized yet and it may not have a
ProductModel
value when called, you should type it as:Then if you want to use a parameter from a nullable class, you can do the following:
This tells Dart that your variable can be
null
;Or, if you know that this variable will never be null, but you’ll assign it a value before using it, you can use the
late
modifier as in your class’ parameters.Dart is now a null-safe language so this
?
is how you tell a variable that it can benull
PS:
About your error on the comments above
type 'Null' is not a subtype of type 'int'
The same applies to your inner variables. They should be
int?
if you are not sure that the givenMap
will give you the value for thatkey
. Or you could do something like: