首页 > 解决方案 > Flutter:如何在动画转换小部件上使用 MediaQuery 的值管理转换

问题描述

首先,我为我的英语道歉。

其次,我在管理 animateTransition 的值时遇到了麻烦。如您所见,我有一个卡片小部件,其位置位于屏幕右侧,MaterialButton 位于屏幕中央。

在此处输入图像描述

定位的小部件的值由 MediaQuery 类给出并保存在位置变量中,但是当我尝试更改位置的值并调用 setSate 函数时,构建方法重做并初始化变量,并且新值总是相同,因为(我认为),因此永远不会看到过渡。

我显示代码。

class _DashboardState extends State<Dashboard> {
final double blur = 30;
final double offset = 20;
final double top = 25;

@override
Widget build(BuildContext context) {
final size = MediaQuery.of(context).size;
double position = -(size.width) * 0.8;

return WillPopScope(
  onWillPop: () async =>
      SystemChannels.platform.invokeMethod('SystemNavigator.pop'),
  child: MaterialApp(
    home: Scaffold(
      body: SafeArea(
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Positioned(
              right: position,
              child: AnimatedContainer(
                duration: Duration(milliseconds: 500),
                curve: Curves.decelerate,
                child: Card(
                  elevation: 8,
                  color: Colors.red,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10),
                  ),
                  child: Container(
                    width: size.width * 0.9,
                    height: size.height * 0.8,
                  ),
                ),
              ),
            ),
            Center(
              child: MaterialButton(
                color: Colors.black,
                child: Text("mover"),
                onPressed: () {
                  setState(() {
                    position = 0;
                  });
                },
              ),
            )
          ],
        ),
      ),
    ),
  ),
);

} }

当我尝试取出变量时,我不能因为 mediaQuery 中的上下文依赖关系而无法初始化请求变量以获取设备的大小,并进入初始状态。管理此类问题的任何建议。

感谢您的关注

标签: flutterflutter-animation

解决方案


推荐阅读