我有一个用于创建侧边栏菜单的小部件:
Widget dashboard(context) {
return Material(
elevation: 8,
color: backgroundColor,
child: Container(
padding: const EdgeInsets.only(left: 16, right: 16, top: 48),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
InkWell(child: Icon(Icons.menu, color: Colors.white), onTap: () {
setState(() {
isCollapsed = !isCollapsed;
});
},),
Text("Corona App", style: TextStyle(fontSize: 24.0, color: Colors.white)),
Icon(Icons.settings, color: Colors.white),
])
],
),
)
);
}
但是我不断收到未定义setState函数的错误。我的主要应用是statefullwidget,所以这很奇怪。谁能帮我吗?
这里是完整代码!
import 'package:flutter/material.dart';
final Color backgroundColor = Color(0xFF4A4A58);
class MenuDashboard extends StatefulWidget {
@override
_MenuDashboardState createState() => _MenuDashboardState();
}
class _MenuDashboardState extends State<MenuDashboard> {
bool isCollapsed = true;
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: backgroundColor,
body: Stack(
children: <Widget>[
menu(context),
dashboard(context),
],
),
);
}
}
Widget menu(context) {
return Padding(
padding: const EdgeInsets.only(left: 16.0),
child: Align(
alignment: Alignment.centerLeft,
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text("Home", style: TextStyle(color: Colors.white, fontSize: 20),),
SizedBox(height: 10.0),
Text("Brochures", style: TextStyle(color: Colors.white, fontSize: 20),),
SizedBox(height: 10.0),
Text("Visitekaartje", style: TextStyle(color: Colors.white, fontSize: 20),),
SizedBox(height: 10.0),
]
)
)
);
}
Widget dashboard(context) {
return Material(
elevation: 8,
color: backgroundColor,
child: Container(
padding: const EdgeInsets.only(left: 16, right: 16, top: 48),
child: Column(
children: <Widget>[
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
mainAxisSize: MainAxisSize.max,
children: [
InkWell(child: Icon(Icons.menu, color: Colors.white), onTap: () {
setState(() {
isCollapsed = !isCollapsed;
});
},),
Text("Corona App", style: TextStyle(fontSize: 24.0, color: Colors.white)),
Icon(Icons.settings, color: Colors.white),
])
],
),
)
);
}
带有错误消息:'未定义功能setState'
setState
是State
类的成员,这意味着它只能在扩展State
的StatefulWidget
类的类内部调用。如果您的类正在扩展StatelessWidget
,则不能调用超类提供的状态成员/方法,包括setState
,initState
和dispose
方法。setState
仅可在StatefulWidget
内部调用。因此,如果我做对了,请在setState
小部件中使用Widget dashboard or menu
。这是行不通的,因为这些小部件在类之外。尝试将widgets
放在类中