Home > front end >  Provider variables returns null value initially
Provider variables returns null value initially

Time:02-20

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 belowenter image description here

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}",

CodePudding user response:

Your cart_notification field is null initially. You should draw the badge only if the cart_notification field is not null.

Try something like:

Provider.of<CartProvider>(context).cart_notification != null ? Text(Provider.of<CartProvider>(context).cart_notification.toString()) : SizedBox.shrink();

CodePudding user response:

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(),
  • Related