如何使用flutter每秒在屏幕上自动移动图像?

wqnecbli  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(128)

这是我的UI

我想把这个人一点一点地移到池塘里,每一个动作都要在每一秒钟里。
这是我的代码

class _QuestionScreenState extends State<QuestionScreen> {
  @override
  void initState() {
    super.initState();
    SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft]);
  }

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(Config.app_SelectionPageBackground1),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            SafeArea(
              child: Column(
                children: <Widget>[
                  Center(child: Padding(
                    padding: const EdgeInsets.only(right: 700.0,top: 200),
                    child: Image.asset(Config.app_man),
                  )),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

当那个人走到池塘边时,他应该停止移动。如何使用Flutter?

xwmevbvl

xwmevbvl1#

创建一个保存当前秒的变量:

int seconds = 0;

我们可以使用AnimatedPosition、Transform.translate等在屏幕上移动图像。找到你需要的小部件,我将使用Transform.translate。将你的图像包裹在一个Transform中。

Transform.translate(
  offset: Offset(seconds * 10,0),
  child: yourImage,
)

您必须提供偏移。Offset构造函数中的第一个值是x坐标,因此每秒我们向右移动更多(10,20,30)。你可以改变10.0,只是一个随机数,我用在这里。
要每秒移动角色,您可以使用计时器。
使用此函数启动计时器:

void startTimer() {
 
   Timer.periodic(
     Duration(seconds: 1),
    (Timer timer) {
       setState(() {
          seconds = seconds + 1;
        });
    },
  );
}

调用函数开始角色的移动。

相关问题