先放上完整异常信息
Another exception was thrown: ‘package:flutter/src/widgets/framework.dart’: Failed assertion: line 4606 pos 14: ‘owner!._debugCurrentBuildTarget == this’: is not true.
出现这个报错结果一般都是代码写昏头了。
1
我的代码中出错的地方:
/这个list是放界面的
List pages=[
HomePage(),
Forum(),
SelfCenter(),
];
class HomePage extends StatefulWidget {
const HomePage({super.key});
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _curIndex=0;
Widget getPage(){
return pages[_curIndex];///留意这里
}
Widget build(BuildContext context) {
return Scaffold(
appBar: const PreferredSize(
preferredSize: Size.fromHeight(1),
child: Divider(),
),
body: getPage(), //还有这里
bottomNavigationBar: BottomNavigationBar(
iconSize: 30,
currentIndex: _curIndex,
onTap: (value) {
setState(() {
_curIndex = value;
});
},
items: [
//这里已经写了正确的逻辑了
],
),
);
}
}
相信已经有明眼人看出来了,HomePage的build的body引用了pages列表,可以随着底部按钮的点击切换对应页面,但是我的第一个列表元素放的是HomePage…,而body需要的是Widget,我HomePage build函数返回的是个Scafflod…
所以一般的情况下应该pages中应该是
List pages=[
Home(),
Forum(),
SelfCenter(),
];
这三个页面应该都是Widget,依托HomePage(Scafflod)管理
2
在网上查资料的时候,还有可能是在写根Widget的时候没有使用MaterialApp包裹你的组件
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget{
const MyApp({super.key});
State<MyApp> createState() => _MyAppState();
}
class _MyApp extends State<MyApp>{
Widget build(BuildContext context){
return Container(
child: ///此处逻辑已写好
);
}
}