I am learning Flutter / Dart and when doing the exercise in this video I have encountered an error that from what I understand is due to the null-safety feature and because the example is from a previous version, the problem appears .
import 'package:flutter/material.dart';
class OurImage extends StatelessWidget {
final String pathImage;
final double widthImage;
final double heightImage;
OurImage({this.pathImage, this.heightImage, this.widthImage});
@override
Widget build(BuildContext context) {
final photo = Container(
width: this.widthImage,
height: this.heightImage,
margin: EdgeInsets.only(right: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(this.pathImage), fit: BoxFit.cover)),
);
return photo;
}
}
The parameter 'pathImage' 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.
When reading these errors 1, 2, 3 about null-safety I thought about correcting the error that appears to me by adding "?" and "!" to my code, with which I validate that the errors no longer appear.
import 'package:flutter/material.dart';
class OurImage extends StatelessWidget {
final String? pathImage; //change here
final double? widthImage; //change here
final double? heightImage; //change here
OurImage({this.pathImage, this.heightImage, this.widthImage});
@override
Widget build(BuildContext context) {
final photo = Container(
width: this.widthImage,
height: this.heightImage,
margin: EdgeInsets.only(right: 20.0),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage(this.pathImage!), fit: BoxFit.cover)), //change here
);
return photo;
}
}
Is the way I have obtained to fix it correct? How should I create the variables of the OurImage class so that it does not generate this error?
widthImageandheightImagenullable looks okay. MakingpathImagenullable looks wrong since you later unconditionally usepathImage!, which asserts thatpathImageis notnull. That would result in a runtime crash ifpathImagewas not set. A more appropriate fix would be: A. makepathImagenon-nullable and make it arequiredargument to the constructor; B. check ifpathImageisnulland conditionally useAssetImage; C. makepathImagenon-nullable and initialize it to some default, non-nullvalue if not provided as a constructor argument. - jamesdlin