Variable's value from Provider Controller returns null when the app is reloaded.
My appbar's cart icon actually shows how items are added to the cart. But when I start the app first time, it shows null as seen below
But when I add a product to the cart, it shows the number of added items correctly.
Here's my code for the appbar's cart notification icon which is a text widget inside Stack.
"${Provider.of<CartProvider>(context, listen: true).cart_notification}",
In case you want to show 0
when app starts you just need to initial cart_notification
like this:
class CartProvider extends ChangeNotifier {
// ...
int cart_notification = 0;
// ...
}
but if you want to show nothing when app starts you can do it like this:
final cartProvider = Provider.of<CartProvider>(context);
final themeData = Theme.of(context);
// ...
cartProvider.cart_notification != null
? Container(
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(5.0)),
color: Colors.black,
),
padding: const EdgeInsets.all(2.0),
child: Text(
"${cartProvider.cart_notification}",
style: themeData.textTheme.bodyText2!.apply(
color: Colors.white,
),
),
)
: const SizedBox.shrink(),
Update:
and you have to update cart_Notification
in getallcart
method:
class CartProvider extends ChangeNotifier {
// ...
Future<void> getallcart() async {
cartproducts = await database.fetchall();
cart_notification = await database.cartNotificationNumber(); // add this line
notifyListeners();
}
// ...
}