【问题标题】:Flutter: Animate a widget's height back to its original content heightFlutter:将小部件的高度动画化回其原始内容高度
【发布时间】:2022-11-13 23:32:01
【问题描述】:

我一直想知道AnimatedContainer 非常灵活。让我感到困惑的是,如果我们可以将Container 设置为小于实际内容的动画,我们如何让它回到默认的内容高度?这是内容的高度取决于其中的内容。

我现在没有真正的用例,但我可以看到它被使用,例如,如果容器内部有一个“ListView”(特此不显示偏移错误)。

我尝试使用 null 但显然它不能为空。

double height = 100;

@override
Widget build(BuildContext context) {
  return Scaffold(
    body: GestureDetector(
      onTap: () {
        setState(() {
          height = height == 100 ? null : 100;
        });
      },
      child: Center(
        child: AnimatedContainer(
          curve: Curves.bounceOut,
          duration: const Duration(milliseconds: 500),
          width: 100,
          height: height,
          color: Colors.deepPurple,
          child: Text('This text set to be much larger than 100 aaaaaaaaaa aaaaaaaa aaaaaaaaa aaaaaaaa.',
            style: TextStyle(
              fontSize: 30,
              color: Colors.white,
            )
          )
        ),
      ),
    )
  );
}

错误

Error: A value of type 'double?' can't be assigned to a variable of type 'double' because 'double?' is nullable and 'double' isn't.
            height = height == 100 ? null : 100;

我试图通过隐式动画来解决这个问题,但我猜答案是明确的。希望听听大家的想法。

【问题讨论】:

    标签: flutter dart flutter-animation dart-null-safety


    【解决方案1】:

    当您将 null 定义为 non-nullable 时,您将其传递给 height 变量,将您的变量更改为:

    double? height = 100;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      • 2012-07-08
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 2021-05-12
      相关资源
      最近更新 更多