【问题标题】:Flutter - AnimatedSize not animating when setting start height to MediaQuery heightFlutter - 将开始高度设置为 MediaQuery 高度时,AnimatedSize 没有动画
【发布时间】:2019-02-21 07:15:18
【问题描述】:

我不知道怎么了...

当我使用 0.0 AnimatedSize 的静态高度时,小部件会生成动画。但是当我设置 topLayoutHeight = MediaQuery.of(context).size.height 没有任何反应。

这是我的代码:

double topLayoutHeight = 0.0;

setHeight(){
    topLayoutHeight = MediaQuery.of(context).size.height - 200;
}

我的小部件:

@override
  Widget build(BuildContext context) {
    setHeight();
    ...
    ...
    new AnimatedSize(
                            curve: Curves.fastOutSlowIn,
                            vsync: this,
                            child:
                              new ClipPath(
                                clipper: CustomShapeClipper(),
                                child: Container(
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(colors: [color1, color2]),
                                  ),
                                  height: topLayoutHeight,
                                ),
                              ), duration: new Duration(seconds: 2),
                          )


...
...

    new RaisedButton(
                                onPressed: () {
                                  setState(() {
                                    shrinkOnClick = false;
                                    topLayoutHeight = 360.0;
                                  });
                                },
                                shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.vertical(
                                      top: Radius.circular(15.0),
                                      bottom: Radius.circular(15.0)
                                    )),
                                child: new Text('Brands',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 16,
                                    fontWeight: FontWeight.bold
                                  ),
                                ),
                                color: Color(0x33FFFFFF),
                                elevation: 0,
                              )

如果我从不做setHeight(),一切都会正常。

为什么我不能用MediaQuery.of(context).size.height动态设置高度?

【问题讨论】:

  • build() 修改状态通常是一个非常糟糕的主意。 build 方法不应该有副作用,只构建 widget 树并返回它。

标签: flutter flutter-layout flutter-animation


【解决方案1】:

改用didChangeDependencies

@override
void didChangeDependencies() {
  super.didChangeDependencies();
  setState(() => topLayoutHeight = MediaQuery.of(context).size.height - 200);
}

【讨论】:

  • 感谢您的回答! :)
猜你喜欢
  • 1970-01-01
  • 2022-11-13
  • 1970-01-01
  • 2019-02-04
  • 2023-03-04
  • 2017-03-27
  • 1970-01-01
  • 1970-01-01
  • 2015-03-05
相关资源
最近更新 更多