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

Flutter错误:返回类型StopWatchWidgetState不符合Widget类型要求

Flutter页面跳转报错:传入State类而非Widget类的解决方案

错误原因

你在跳转路由时犯了基础错误:直接实例化StopWatchWidgetState(State类)作为页面Widget,但Flutter的Navigator.push要求传入继承自Widget的类,这里应该使用StopWatchWidget(StatefulWidget类)。State类是由StatefulWidget的createState()方法自动创建的,不能直接作为页面路由使用。

修正后的按钮代码

把跳转代码里的StopWatchWidgetState()替换为StopWatchWidget()即可:

floatingActionButton: FloatingActionButton(
    backgroundColor: Colors.grey.shade800,
    onPressed: () {
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => StopWatchWidget()), // 此处修正
      );
    },
    child: const Icon(
      Icons.timer,
      color: Colors.orangeAccent,
    ),
  ),

额外优化建议

  1. 定时器性能优化:当前使用Duration(milliseconds: 1)的定时器会每秒触发1000次setState,严重消耗性能。建议调整为Duration(milliseconds: 100),秒级显示不需要1毫秒精度,可大幅降低页面刷新频率。
  2. 变量定义位置修正:build方法内定义的bool isPressed = false会在每次页面重建时重置,应将其移至State类的成员变量区域:
class StopWatchWidgetState extends State<StopWatchWidget> {
  bool isPressed = false; // 移至此处作为成员变量
  final Stopwatch _stopwatch = Stopwatch();
  // ... 其余代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 12:00:14