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

Flutter初学者创建双页面应用时遇到State类型不匹配错误求助

解决Flutter中StatefulWidget与State类型不匹配的错误

嘿,我看到你遇到的这个类型错误啦,这是Flutter新手很容易踩的小坑,别着急,咱们一步步来解决它!

错误原因分析

你收到的错误信息:

StatefulWidget.createState must return a subtype of State
The createState function for FirstPage returned a state of type _FirstPageState, which is not a subtype of State, violating the contract of createState.

本质问题是**FirstPage这个StatefulWidget对应的State类类型不匹配**:

  • 你定义的FirstPage是一个独立的StatefulWidget,但它的createState方法返回的是State<MyApp>,而不是State<FirstPage>
  • 同时你的_FirstPageState继承的是State<MyApp>,这完全绑定错了父Widget类型,框架自然会报错

修正后的代码

只需要把FirstPage的createState返回类型和_FirstPageState的继承类型改成和FirstPage绑定即可:

void main() { runApp(MyApp()); } 
class MyApp extends StatefulWidget { 
  MyApp({super.key}); 
  @override 
  State<MyApp> createState() => _MyAppState(); 
} 
class _MyAppState extends State<MyApp> { 
  @override 
  Widget build(BuildContext context) { 
    return MaterialApp( 
      home: FirstPage(), 
    ); 
  } 
} 
class FirstPage extends StatefulWidget { 
  FirstPage({super.key}); 
  // 这里把返回类型改成State<FirstPage>
  @override 
  State<FirstPage> createState() => _FirstPageState(); 
} 
// 这里把继承的State类型改成FirstPage
class _FirstPageState extends State<FirstPage> { 
  String bottonName = 'click'; 
  int currentIndex = 0; 
  @override 
  Widget build(BuildContext context) { 
    return Scaffold( /* 你的页面内容 */ );
  }
}

关键知识点解释

在Flutter中,每个StatefulWidget对应的State类必须遵循State<T>的泛型约束,其中T就是该State所属的StatefulWidget类。这样做的目的是让State能够通过widget属性安全地访问对应StatefulWidget的成员变量,同时Flutter框架也能正确地管理这个Widget的生命周期和状态更新。

以后写StatefulWidget的时候,记得保持Widget和State的泛型类型一致,就不会再遇到这类问题啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 12:47:37