我试图在onPress中使用setState方法更改容器的颜色,但应用程序因未定义setState错误而崩溃。我想寻求帮助。任何帮助提供者都将不胜感激。谢谢
import 'package:flutter/material.dart';
import 'AllContainers.dart';
import 'ColumnContainer.dart';
import 'AllConstants.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
enum AgeStatus { child, old }
class MyHomePage extends StatefulWidget {
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AgeStatus? ageStatus;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Practising_Cards'),
),
body: Column(
children: <Widget>[
Expanded(
child: Row(
children: [
Expanded(
child: AllContainers(
onPress: () {
setState(() {
ageStatus = AgeStatus.child;
});
},
colors: ageStatus == AgeStatus.child
? activeColor
: deactiveColor,
mycard: MyColumnItems(FontAwesomeIcons.mars, 'FEMALE'),
),
),
Expanded(
child: AllContainers(
colors: ageStatus == deactiveColor
? activeColor
: deactiveColor,
onPress: () {
setState(() {
ageStatus = AgeStatus.old;
});
},
mycard: MyColumnItems(FontAwesomeIcons.mars, 'FEMALE'),
),
)
],
),
),
Container(
margin: EdgeInsets.only(top: 5),
width: double.infinity,
height: 50,
color: Colors.red,
),
],
),
);
}
}
这是容器类
import 'package:flutter/material.dart';
import 'NewMain.dart';
class AllContainers extends StatelessWidget {
final Color colors;
final Widget mycard;
final Function onPress;
AllContainers(
{required this.colors, required this.mycard, required this.onPress});
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress(),
child: Container(
child: mycard,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: colors,
borderRadius: BorderRadius.circular(20),
),
),
);
}
}
我尝试在State中创建一个带有setState
的函数,并将该函数传递给我的onPress方法,但也不起作用。
AllContainers的属性onTap
的类型为Function
。
但我认为你的意图是VoidCallback
类型。
因此,您必须将onTap
属性的类型从Function
更改为VoidCallback
并且您必须传递的不是onPress()
而是onPress
。
class AllContainers extends StatelessWidget {
final Color colors;
final Widget mycard;
// final Function onPress;
final VoidCallback onPress;
AllContainers({
required this.colors,
required this.mycard,
required this.onPress,
});
Widget build(BuildContext context) {
return GestureDetector(
// onTap: onPress(),
onTap: onPress,
child: Container(
child: mycard,
margin: EdgeInsets.all(10),
decoration: BoxDecoration(
color: colors,
borderRadius: BorderRadius.circular(20),
),
),
);
}
}
您应该在AllContainers
中使用最终VoidCallback onPress
而不是最终Function onPress
这是您应该用来解决问题的类。
class AllContainers extends StatelessWidget {
final Color colors;
final Widget myCard;
final VoidCallback onPress;
const AllContainers(
{super.key,
required this.colors,
required this.myCard,
required this.onPress});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onPress,
child: Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: colors,
borderRadius: BorderRadius.circular(20),
),
child: myCard,
),
);
}
}
请注意,要在您的编码中使用注释和camelCase。快乐编码…