Flutter AppBar 多次使用组件

Flutter AppBar multiple time using component

我创建了 Appbar 组件并在每个内页中调用,现在我需要在此处为​​购物车动态计数实现动态值,当我尝试调用未来函数或设置状态时这里也不起作用,因为它给我错误,因为我没有使用状态小部件的状态,如果有人有相同的示例,那将是可观的。

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)),
              )
            ],
          ),
        )
      ]
    )
  ),
],
  );
}

您可以将 totalCartItems 之类的整数传递给构造函数。
喜欢

AppBarComponent({Key key, int totalCartItems})

并稍后使用

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

现在,如果您要在状态 class 中更新 totalCartItems 的状态,同样会反映在您的 appBar 中。
只需将单个实例设为 totalCartItems.