I am getting imageUrl from another page. and I want to use the "imageUrl" inside of "theimage" but I cannot access it. I am facing this error.
The instance member 'widget' can't be accessed in an initializer. Try replacing the reference to the instance member with a different expression
class ProductCard extends StatefulWidget {
final String imageUrl;
ProductCard(
{this.imageUrl,});
@override
State<ProductCard> createState() => _ProductCardState();
}
class _ProductCardState extends State<ProductCard> {
// I can not access widget.imageUrl in here
final theImage = Image.network("${widget.imageUrl}", fit: BoxFit.cover);
/// Did Change Dependencies
@override
void didChangeDependencies() {
precacheImage(theImage.image, context);
super.didChangeDependencies();
}
@override
Widget build(BuildContext context) {
return Container(
child:theImage;
);
}
}
CodePudding user response:
You are using named constructor ProductCard
make imageUrl
required nullable ,or provide default value.
const ProductCard(
{required this.imageUrl,});
And use initState
for initialization.
late final Image theImage;
@override
void initState() {
theImage = Image.network("${widget.imageUrl}", fit: BoxFit.cover);
super.initState();
}
Next remove ;
from end of theImage
or use ,
.
@override
Widget build(BuildContext context) {
return Container(child: theImage);
}