You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中3D模型无法旋转问题求助

解决flutter_cube模型无法旋转的问题

常见原因及修复方案

  • 未触发Widget状态重建:如果角度变量不是StatefulWidget的状态变量,或者更新角度时未调用setState(),CubeWidget无法感知到参数变化。必须在更新角度后调用setState()触发UI刷新。
  • Timer使用不规范:确保Timer在State的initState()中初始化,并在dispose()中销毁,避免内存泄漏同时保证定时器生命周期与页面一致。
  • 旋转参数绑定错误:flutter_cube的Cube组件rotation参数必须绑定到动态更新的状态变量,而非固定值。

可运行示例代码

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_cube/flutter_cube.dart';

class RotatingModelPage extends StatefulWidget {
  const RotatingModelPage({super.key});

  @override
  State<RotatingModelPage> createState() => _RotatingModelPageState();
}

class _RotatingModelPageState extends State<RotatingModelPage> {
  late Object _3dModel;
  double _yRotation = 0;
  Timer? _rotationTimer;

  @override
  void initState() {
    super.initState();
    // 加载OBJ/GLB模型
    _3dModel = Object(
      fileName: 'assets/models/your_model.obj', // 替换为你的模型路径
      scale: Vector3(1, 1, 1),
    );
    // 启动定时旋转
    _rotationTimer = Timer.periodic(const Duration(milliseconds: 50), (timer) {
      setState(() {
        _yRotation += 0.5;
        if (_yRotation >= 360) _yRotation = 0;
      });
    });
  }

  @override
  void dispose() {
    _rotationTimer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Cube(
          onSceneCreated: (Scene scene) {
            scene.world.add(_3dModel);
            scene.camera.position = Vector3(0, 0, 10);
          },
          rotation: Vector3(0, _yRotation, 0),
        ),
      ),
    );
  }
}

额外优化建议

  • 替换Timer为动画系统:如果需要更平滑的旋转效果,推荐使用AnimationController结合addListener()实现,避免固定间隔定时器可能带来的卡顿。
  • 验证模型加载:确认模型路径已正确配置到pubspec.yaml的assets中,若模型加载失败也会表现为静止状态。
  • 调试角度变化:在setState()前后打印角度值,确认变量确实在更新,排除逻辑错误。

内容的提问来源于stack exchange,提问作者Bert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 18:44:57