【问题标题】:Obtaining parent size to use within child获取要在子级中使用的父级大小
【发布时间】:2020-06-20 14:46:09
【问题描述】:

我试图在我的 Expanded 小部件中放置一个 AnimatedContainer(因为将 AnimatedContainer 作为父级会引发 Flex 错误),因为我正在使用一个事件在三个可能的条件下调整两个 Expanded 容器的大小。两者都以 50/50 的弹性尺寸开始,然后在第二个条件下变为 25/75,最后一个条件为 75/25。它在没有 Animated 容器的情况下运行良好,但大小转换是即时的,我希望它具有动画效果。

这基本上是目前的设置方式:

  Flex(
    direction: Axis.horizontal,
    crossAxisAlignment: CrossAxisAlignment.end,
    children: <Widget>[
      Expanded(  // <---  I would like to get the current width of this
        flex: (target[expController.target]["newsWidth"]),
        child: AnimatedContainer(
          width: ?, // <-- and use it here
          duration: Duration(milliseconds: 500),
          curve: Curves.fastOutSlowIn,
          child: NewsMainHome(),
        ),
      ),
      Spacer(flex: target[expController.target]["spacer"]),
      Expanded(
        flex: (target[expController.target]["changeLogWidth"]),
        child: AnimatedContainer(
          width: ?, // Set to parent size
          duration: Duration(milliseconds: 500),
          curve: Curves.fastOutSlowIn,
          child: ChangeLogList(),
        ),
      ),
    ],
  ),

如果能够将 AnimatedContainer 宽度设置为父级 Expanded 宽度的大小,那么当 Expanded flex 值从事件发生变化时,它会为大小转换设置动画,但我还没有找到合适的方法去做吧。有什么想法/建议吗?

谢谢,
-MH

【问题讨论】:

    标签: flutter


    【解决方案1】:

    你可以使用LayoutBuilder

    Expanded(
      flex: (target[expController.target]["changeLogWidth"]),
      child: LayoutBuilder(
        builder: (context, constraints) => AnimatedContainer(
          width: constraints.maxWidth,
          duration: Duration(milliseconds: 500),
          curve: Curves.fastOutSlowIn,
          child: ChangeLogList(),
        ),
      ),
    ),
    

    或者更简单的试试这个

    Expanded(
      flex: (target[expController.target]["changeLogWidth"]),
      child: AnimatedContainer(
        width: double.infinity,
        duration: Duration(milliseconds: 500),
        curve: Curves.fastOutSlowIn,
        child: ChangeLogList(),
      ),
    ),
    

    【讨论】:

    • Frederick,我尝试了你提到的一些变体,以及 Shawn 的回复,但不幸的是,在这种情况下,它们都不适合我。最终解决的问题实际上只是将 Expanded 框和关联的 Flex 容器一起移除并仅使用 AnimatedContainer。然后使用扩展控制器并将其用于 AnimatedContainer 宽度而不是 flex。现在事情进展顺利。 i.imgur.com/mM2S5Uv.gifv 感谢你们抽出宝贵时间提供帮助。
    【解决方案2】:

    如前所述,使用 LayoutBUilder 获取大小。不过,对于这个用例,您可以直接为 Flex 设置动画:

    var leftFlex = 75;
    return TweenAnimationBuilder<int>(
      tween: Tween(begin: 50, end: leftFlex),
      duration: Duration(milliseconds: 700),
      builder: (_, value, __){
        return Row(
          children: [
            Expanded(flex: value, child: leftContent),
            Expanded(flex: 100 - value, child: rightContent),
          ],
        )
      },
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-19
      • 1970-01-01
      • 2014-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多