Usman Hafeez
Usman Hafeez

Reputation: 59

Null check operator used on a null value while using variable from provider into another screen

I am using provider for statemanagement. when i call nullable (int? tipIndex) variable using provider in another class i must have to put ! operator... when i put ! opertaor i get error that null check opertaor used on null value... how can i keep my variable null initially.

Here is provider class code :

 int? tipIndex;
  List<double> tipList = [2, 3, 5];

here i am assigning tipIndex the value of index from ListView.builder

setState(() {
               cart.tipIndex = index;
               });

here i am using values

cart.tipList[index] == cart.tipList[cart.tipIndex!]

here is Complete list View builder

ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: cart.tipList.length,
  shrinkWrap: true,
  itemBuilder: ((context, index) {
    return tipContainer(context, cart.tipList[index].toInt(),
        () {
      setState(() {
        cart.tipIndex = index;
      });
    },
        cart.tipList[index] == cart.tipList[cart.tipIndex]
            ? const Color.fromARGB(255, 243, 164, 1)
                .withOpacity(0.5)
            : Colors.black54,
        cart.tipList[index] == cart.tipList[cart.tipIndex]
            ? Colors.white
            : Colors.transparent);
  }),
);

Here is UI

Upvotes: 2

Views: 118

Answers (1)

lepsch
lepsch

Reputation: 10319

You should build the UI conditionally by checking if cart.tipIndex is null or not before actually using it. It's going to be something as below:

ListView.builder(
  scrollDirection: Axis.horizontal,
  itemCount: cart.tipList.length,
  shrinkWrap: true,
  itemBuilder: ((context, index) {
    return tipContainer(
      context,
      cart.tipList[index].toInt(),
      () {
        setState(() {
          cart.tipIndex = index;
        });
      },
      // Here
      cart.tipIndex != null && cart.tipList[index] == cart.tipList[cart.tipIndex!]
          ? const Color.fromARGB(255, 243, 164, 1)
              .withOpacity(0.5)
          : Colors.black54,
      // Here
      cart.tipIndex != null && cart.tipList[index] == cart.tipList[cart.tipIndex!]
          ? Colors.white
          : Colors.transparent,
    );
  }),
);

Upvotes: 1

Related Questions