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

Flutter:在Stateful Widget中调用类方法触发构造函数错误的咨询

问题原因

你把game.launchNewGame()直接写在了NewGameRoute类的顶层成员区域,这是Dart语法不允许的。类的顶层区域只能定义成员变量、构造函数、方法这类声明性内容,不能直接执行函数调用这类可执行语句。编译器会把这种写法误判成一个名称非法的构造函数,所以才抛出了"The name of a constructor must match the name of the enclosing class"错误。

修复方案

根据你的需求,有两种可行的修复方式:

方式一:在Widget构造函数里调用

如果想在NewGameRoute实例化时就启动游戏,把方法调用放到构造函数体内就行:

class NewGameRoute extends StatefulWidget {
  NewGameRoute({super.key}) {
    // 构造函数体内调用方法
    game.launchNewGame();
  }

  Game game = Game();

  @override
  State<NewGameRoute> createState() => _NewGameRouteState();
}

方式二:在State类里调用(更推荐)

Flutter里StatefulWidget本身是不可变的,业务逻辑一般放在对应的State类里,这是官方推荐的写法:

class NewGameRoute extends StatefulWidget {
  NewGameRoute({super.key});

  @override
  State<NewGameRoute> createState() => _NewGameRouteState();
}

class _NewGameRouteState extends State<NewGameRoute> {
  late Game game;

  @override
  void initState() {
    super.initState();
    game = Game();
    // 在State初始化阶段调用游戏启动方法
    game.launchNewGame();
  }

  @override
  Widget build(BuildContext context) {
    // 这里写你的UI代码
    return Scaffold(
      body: Center(child: const Text("新游戏")),
    );
  }
}

内容的提问来源于stack exchange,提问作者نظامی گنجوی

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:05:06