我尝试使用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方法,但也不起作用
3条答案
按热度按时间7ajki6be1#
你把
function
放在VoidCallBack
上0pizxfdo2#
所有容器的属性
onTap
具有类型Function
。但我认为你的意图是
VoidCallback
类型。因此,必须将
onTap
属性的类型从Function
更改为VoidCallback
你必须通过的不是
onPress()
而是onPress
。uurity8g3#
你应该在你的
AllContainers
里面使用final VoidCallback onPress
而不是final Function onPress
这是你应该用来解决你的问题的类。请注意,使用注解和使用camelCase在您的编码。快乐编码...