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,
),
),
),
);
}
}
2
Answers
The type of
product
from the callback parameter isObject
because you didn’t specify the generic type when using theConsumer
.When dealing with nullable value that needs to be retrieved as non-nullable, you have two options:
!
if you’re sure it’s not null?.
and provide a "default case"(In this case, if
product
isnull
the value of this expression will befalse
See also: