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

