Home > Back-end >  LateInitializationError: Field 'productItem' has not been initialized
LateInitializationError: Field 'productItem' has not been initialized

Time:09-13

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);
                },
              ))
        ],
      ),
    );
  }
}

CodePudding user response:

late means you are telling Flutter that i will make sure that this field gets initialized, don't do null checks on this variable. But you are using late and not initializing productItem, which is resulting in runtime error

CodePudding user response:

You need to start productItem variable. When you use late, you guarantee that you will start right after this variable.

Use

Product product = Product(id, name);

Instead of

late Product product;

or

late Product product;
product = Product(id, name);
  • Related