Search code examples
componentsflutterappbar

Flutter AppBar multiple time using component


I created Appbar component and calling in every inner page, Now I need to implement dynamic value here for the cart dynamic count when I am trying to call a future function or set state also not working here it gives me error because of state widget i am not using, if anyone has an example for the same that will appreciable.

class AppBarComponent extends AppBar {

  final _formKey = new GlobalKey<FormState>();
  AppBarComponent({Key key})
: super(
key: key,
backgroundColor: Colors.greenAccent,
centerTitle: true,
title: Image.asset(
    'images/logo.png',
    width: 120.0,
    //height: 20.0,
    //fit: BoxFit.cover
),
actions: <Widget>[
  new IconButton(
    icon: Stack(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(right: 8.0,top: 4.0),
          child: Icon(Icons.shopping_cart,color: Colors.white,),
        ),
        Positioned(
          top: 0.0,
          right: 1.0,
          child: new Stack(
            children: <Widget>[
              Icon(Icons.brightness_1, size: 16.0, color: Colors.red[800]),
              Positioned(
                top: 1.0,
                right: 4.0,
                child: new Text("2",
                  style: new TextStyle(
                    color: Colors.white,
                    fontSize: 12.0,
                    fontWeight: FontWeight.w500)),
              )
            ],
          ),
        )
      ]
    )
  ),
],
  );
}

Solution

  • You could pass an integer like totalCartItems with the constructor.
    Like

    AppBarComponent({Key key, int totalCartItems})
    

    and use the same later as

    Positioned(
                top: 1.0,
                right: 4.0,
                child: new Text(totalCartItems.toString,
                  style: new TextStyle(
                    color: Colors.white,
                    fontSize: 12.0,
                    fontWeight: FontWeight.w500)),
              )
    

    Now if you will update the state of totalCartItems in your state class, the same will be reflected in your appBar.
    Just make to a single instance to totalCartItems.