【问题标题】:How to rebuild a particular widget property instead of the whole widget?如何重建特定的小部件属性而不是整个小部件?
【发布时间】:2019-11-19 06:59:12
【问题描述】:

我正在制作一个应用程序并显示循环进度指示器,我使用了 modal_progress_hud 库,当我将 inAsyncCall 的状态设置为真或假时,它会在 modal_progress_hud 内重建其所有子小部件。而且我不想一次又一次地重建所有的 UI。它通过增加 GPU 的使用来降低应用程序的效率。有没有其他方法可以让它变得更好,我们只需更改属性并仅重建小部件的该属性,而不是整个屏幕和其中的小部件。

  bool circularindicator = false;
  Color circularColor;
  double circularOpacity;

              child: ModalProgressHUD(
                inAsyncCall: circularindicator,
                child: body,
                color: circularColor,
                opacity: circularOpacity,
              ),

在正文中,我们在列表视图中拥有所有小部件。 在按下登录按钮后,我们调用 showProgress() 方法并设置状态并重建小部件。

  @override
  showProgress() {
    setState(() {
      circularindicator = true;
      circularOpacity = 0.5;
      circularColor = Colors.grey;
    });
  }

【问题讨论】:

  • check Flutter: Don’t Fear the Garbage Collector - 它说:“那么 Flutter 开发人员应该害怕垃圾收集器吗?随着 Flutter 创建和销毁对象的频率很高,开发人员是否应该采取措施限制这种行为?不是很少看到新的 Flutter 开发人员创建对他们知道不会随时间改变的小部件的引用,并将它们置于状态,以便它们不会被破坏和重建。不要这样做。”

标签: user-interface flutter dart rebuild state-management


【解决方案1】:

创建您的班级StatelessWidget 并使用Provider Package 进行状态管理。在小部件构建函数中保留 Provider 侦听器 false 并使用 Consumer Widget 包装可更改的小部件。

 Widget build(BuildContext context) {
  final cart = Provider.of<Cart>(context, listen: false);
  return GridTileBar(
        leading: Consumer<Product>(
          builder: (ctx, product, child) => IconButton(
            onPressed: () {
              product.toggleFavoriteStatus();
            },
            icon: Icon(product.isFavorite ? Icons.favorite : Icons.favorite_border),
            color: Theme.of(context).accentColor,
          ),
        ),
        trailing: IconButton(
          icon: Icon(Icons.shopping_cart),
          onPressed: () {
            cart.addItem(product.id, product.title, product.price);
          },
          color: Theme.of(context).accentColor,
        ),
        backgroundColor: Colors.black87,
        title: Text(product.title),
      );
}

有关提供程序包的更多详细信息:State Management Using Provider

【讨论】:

    猜你喜欢
    • 2019-01-14
    • 2016-11-07
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2021-09-26
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多