Anesu Mazvimavi
Anesu Mazvimavi

Reputation: 139

LateInitializationError: Field 'productItem' has not been initialized

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

Upvotes: 0

Views: 57

Answers (2)

Cristiano Haas
Cristiano Haas

Reputation: 172

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);

Edit:

I'm adding below the code I put in the comment link of this answer and which @Anesu said worked.

class ProductItem {
  String id;
  String bottleName;
  String imgUrl;
  String price;
  Bottle bottle;

  ProductItem({required this.id, required this.bottleName, required this.imgUrl, required this.price});
}

class ProductItemPage extends StatefulWidget {
  ProductItem item;
  
  ProductItemPage(
      {Key? key,
      required this.item})
      : super(key: key);

  @override
  State<ProductItemPage> createState() => _ProductItemPageState();
}

class _ProductItemPageState extends State<ProductItemPage>
    with AutomaticKeepAliveClientMixin {
  
   late ProductItem productItem;
  
  @override
  void initState() {
    super.initState();
    productItem = widget.item;
  }
  
  @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.bottle,
                      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);
                },
              ))
        ],
      ),
    );
  }
}

Upvotes: 1

Sanketh B. K
Sanketh B. K

Reputation: 837

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

Upvotes: 2

Related Questions