如何 'setState' 仅应用程序栏图标而不是 'notifyListeners'

How to 'setState' only to the appBar icons instead of 'notifyListeners'

我有一个带有一个图标的应用程序栏,这个图标有一个数字,在我更改应用程序中的某些内容后必须更新。我正在使用 notifyListeners(),但是这个命令正在清理我需要的列表,所以我必须在没有 notifyListeners() 的情况下更新应用栏中的那个数字。

我尝试调用 SetState 但它不起作用..有没有办法只更新应用栏?

在我包含更多项目的提供商中:

  void setBadge() {
    _number = number;
    notifyListeners(); // this line I dropped out
  }

应用栏图标小部件:

class AppBarWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<Cart>(
      child: IconButton(
        icon: Icon(Icons.shopping_bag_outlined),
        onPressed: () async {
          Navigator.of(context).pushNamed(ROUTE_CART);
        },
      ),
      builder: (_, cart, child) {
        return BagBadge(
          child: child,
          value: cart.isEmpty ? '' : cart.number.toString(),
        );
      },
    );
  }
}

行李徽章:

class BagBadge extends StatelessWidget {
  final Widget child;
  final String value;

  BagBadge({
    @required this.child,
    @required this.value,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      alignment: Alignment.center,
      children: <Widget>[
        child,
        if (value != '')
          Positioned(
            right: value.length < 4 ? 20 : 10,
            top: 30,
            child: Container(
              padding: EdgeInsets.all(value.length < 4 ? 2 : 3),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10),
                color: Theme.of(context).accentColor
              ),
              constraints: BoxConstraints(
                minHeight: 16,
                minWidth: 16,
              ),
              child: Text(
                value,
                textAlign: TextAlign.center,
                style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
              ),
            ),
          )
      ],
    );
  }
}

编辑:这仅在您使用有状态小部件时有效。对于无状态小部件,不会显示更改。

您可以尝试这样的操作:

import 'package:flutter/material.dart';

class AppBarWidget extends StatefulWidget {
  @override
  _AppBarWidgetState createState() => _AppBarWidgetState();
}

class _AppBarWidgetState extends State<AppBarWidget> {
  int _appBarValue = 0;

  @override
  Widget build(BuildContext context) {
    return Consumer<Cart>(
      child: IconButton(
        icon: Icon(Icons.shopping_bag_outlined),
        onPressed: () async {
          Navigator.of(context).pushNamed(ROUTE_CART);
        },
      ),
      builder: (_, cart, child) {
        return BagBadge(
          child: child,
          value: _appBarValue == 0 ? '' : '$appBarValue',
        );
      },
    );
  }
}

  setAppBarValue(int value) {
     setState(() { _appBarValue = value; });
  }
}

任何时候你想改变这个值,只要调用setAppBarValue()函数。