1

My requirement is something like this: Flutter - change appbar icon when receiving notification

But AppBar 'cart icon' which is to be notified on 'addToCart' button click implemented in another dart file. Am I doing something wrong by placing the AppBar and the rest in two different dart files? Let me know how to proceed.

SantoshKumar
  • 197
  • 2
  • 4
  • 12

1 Answers1

1

You can use a global ValueNotifier variable. Then you can change it's content regardless the page in which you are.

Assuming this variable declaration ValueNotifier cartCounterNotifier = ValueNotifier(0);, you can update your AppBar action like this

appBar: AppBar(
    // title and other
    actions: [
      ValueListenableBuilder(
          valueListenable: cartCounterNotifier,
          builder: (context, cartCounter, child) {
            return Stack(
              children: [
                IconButton(
                  icon: Icon(Icons.shopping_cart_rounded),
                  onPressed: () {},
                ),
                Positioned(
                  child: 0 < cartCounter ? Container(
                    decoration: ShapeDecoration(
                      color: Colors.red,
                      shape: CircleBorder(),
                    ),
                    padding: EdgeInsets.all(2.0),
                    child: Text("$cartCounter", style: TextStyle(
                      color: Colors.white,
                    ),),
                  ) : SizedBox(),
                ),
              ],
            );
          }
      )
    ],
  ),

Update:
So to update your action button, simply change the content of your variable like this

cartCounterNotifier.value = cartCounterNotifier.value + 1; // or another value
dm_tr
  • 4,265
  • 1
  • 6
  • 30
  • thanks for quick reply. I gone through . Let me correct my question: AppBar cart icon which is to be notified on 'addToCart' click implemented on another dart file instead of another class. – SantoshKumar Dec 20 '20 at 20:51
  • not yet :) . please read my above comment for reframed question – SantoshKumar Dec 20 '20 at 20:56