widget_tree_depth_counter

Widget Tree Depth Counter

Pub Package
likes
popularity
pub points

Package Issue
Package License

WidgetTreeDepthCounter 是一个简单的 widget,用于计算嵌套 widget 树的数量,在动态构建界面时非常有用,当知道 widget 的深度很重要时。

Image
WidgetTreeDepthCounter

功能

  • widget 相对于树的深度计数 (所有当前树中 WidgetTreeDepthCounter 的使用都已计算在内,其他类型的 widget 未计算在内)

在以下情况下,此 widget 可以方便地使用

  • 根据 widget 在树中的位置动态管理 widget 的颜色

  • 在一个管理章节编号的应用程序中,如果删除了一个章节,很容易重新编号。

  • 许多其他情况,其中通过固定参数来管理 widget 非常困难,需要根据树的结构进行管理。

 

用法

请务必查看 GitHub 上的示例

Image
在 widget 树中运行的示例

安装

pubspec.yaml

将以下行添加到pubspec.yaml

dependencies:
  widget_tree_depth_counter: <last-release>

and

flutter pub get

从命令行

运行以下命令

flutter pub add provider

基本设置

完整的示例 在此

ParentWidget(
  child: WidgetTreeDepthCounter(
    builder: (context, counter) => //counter=0
      Container(
        color: Theme.of(context)
          .primaryColor
          .withOpacity(counter * 0.05 + 0.05),
          child: WidgetTreeDepthCounter(
            builder: (context, counter) =>//counter=1
                Container(
                    color: Theme.of(context)
                    .primaryColor
                        .withOpacity(counter * 0.05 + 0.05),
                ),
          ),
      ),
  ),
),

WidgetTreeDepthCounter 属性

  • builder:在布局时调用以构建 widget 树的函数,返回 Widget
  • count:通过此参数可以定义或覆盖当前的深度计数。值。

 

在构建 WidgetTreeDepthCounter 时使用当前的 counter

WidgetTreeDepthCounter 使用 Provider 库来计算深度,但如果需要访问当前值来进行(例如)加法运算,可以通过 `Provider` 函数检索计数值。

WidgetTreeDepthCounter(
			count: context.read<DepthCounter>().value + 2,
            builder: (context, counter) =>
                Text(counter.toString()),
          )

显然,要通过 context.read<DepthCounter>() 访问该值,树中至少需要存在一个 WidgetTreeDepthCounter 并且需要 `provider` 包。

 

GitHub

查看 Github