I am building a flutter app and I am getting a LateInitialization error on the productItem field. I made an instance of the ProductItem class so that I could access and pass the instance variables to my methods in the ProductItemState class. I also tried making the field nullable but I then ended up getting a "unexpect null value" error. I'm not sure which other way I can access those instance variables in my ProductItemState class. Please can anyone kindly assist.
class ProductItem extends StatefulWidget {
String id;
String bottleName;
String imgUrl;
double price;
Bottle bottle;
ProductItem(
{Key? key,
required this.id,
required this.bottleName,
required this.imgUrl,
required this.price,
required this.bottle})
: super(key: key);
@override
State<ProductItem> createState() => _ProductItemState();
}
class _ProductItemState extends State<ProductItem>
with AutomaticKeepAliveClientMixin {
late ProductItem productItem;
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
var cart = Provider.of<ShoppingCartProvider>(context);
var favoriteProvider = Provider.of<FavoriteProvider>(context);
return Card(
shadowColor: Colors.grey,
surfaceTintColor: Colors.amber,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
child: Stack(
children: [
Positioned(
right: 0,
child: InkWell(
onTap: () {
favoriteProvider.toggleFavorites(productItem.bottle);
if (favoriteProvider.isExist(productItem.bottle)) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
"Product Added to Favorite!",
style: TextStyle(fontSize: 16),
),
backgroundColor: Colors.green,
duration: Duration(seconds: 1),
),
);
} else {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
"Product Removed from Favorite!",
style: TextStyle(fontSize: 16),
),
backgroundColor: Colors.red,
duration: Duration(seconds: 1),
),
);
}
},
child: favoriteProvider.isExist(productItem.bottle)
? Icon(
Icons.favorite,
color: Colors.redAccent,
)
: Icon(Icons.favorite_border),
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset(
productItem.imgUrl,
height: 200.0,
),
),
Center(
child: Text(productItem.bottleName,
style: const TextStyle(
fontSize: 20.0, fontWeight: FontWeight.bold))),
Center(
child: Text('R${productItem.price}'),
)
],
),
Positioned(
bottom: 0,
right: 10,
child: IconButton(
icon: const Icon(Icons.add_circle),
iconSize: 40.0,
onPressed: () {
cart.addToCart(productItem.id, productItem.bottleName,
productItem.price, productItem.imgUrl);
},
))
],
),
);
}
}