skip to Main Content

I have got two errors for a null check. one for IsFavorite and Try making the access conditional (using ‘?.’) or adding a null check to the target (‘!’)
another one for a null check for toggleFavoritestatus() and The method ‘toggleFavoritestatus’ can’t be unconditionally invoked because the receiver can be ‘null’.
Try making the call conditional (using ‘?.’) or adding a null check to the target (‘!’)

I have added both ?. or !. but all do not work!

here is my code:

import 'package:flutter/material.dart';
import 'package:my_shop/providers/product.dart';

import 'package:my_shop/screens/product_detail_screen.dart';
import 'package:provider/provider.dart';

class ProductItem extends StatelessWidget {

 @override
 Widget build(BuildContext context) {
  final product = Provider.of<Product>(context, listen: false);
  return ClipRRect(
   borderRadius: BorderRadius.circular(10),
   child: GridTile(
    footer: GridTileBar(
        title: Text(
          product.title,
          textAlign: TextAlign.center,
          textScaler: const TextScaler.linear(2 / 3),
        ),
        backgroundColor: Colors.black87,
        leading: Consumer(
            builder: (ctx, product, _) => IconButton(
                  icon: Icon(product.isFavorite
                      ? Icons.favorite
                      : Icons.favorite_border),
                  color: Theme.of(context).colorScheme.secondary,
                  onPressed: () {
                    product.toggleFavoritestatus();
                  },
                )),
        trailing: IconButton(
          icon: const Icon(Icons.shopping_cart),
          color: Theme.of(context).colorScheme.secondary,
          onPressed: () {},
        )),
    child: GestureDetector(
      onTap: () {
        Navigator.of(context).pushNamed(
          ProductDetailScreen.routeName,
          arguments: product.id,
        );
      },
      child: Image.network(
        product.imageUrl,
        fit: BoxFit.cover,
      ),
    ),
  ),
);
}
}

enter image description here

2

Answers


  1. (product?.isFavorite ?: false) ? Icons.favorite : Icons.favorite_border
    
    
    product?.toggleFavoritestatus();
    
    Login or Signup to reply.
  2. The type of product from the callback parameter is Object because you didn’t specify the generic type when using the Consumer.

    Consumer<Product>(
      // ...
    )
    

    When dealing with nullable value that needs to be retrieved as non-nullable, you have two options:

    1. Use ! if you’re sure it’s not null
      product!.isFavorite
      
    2. Use ?. and provide a "default case"
      product?.isFavorite ?? false
      

      (In this case, if product is null the value of this expression will be false


    See also:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search