Am trying to change the color of my container using the setState Method in onPress
but the app crashes with an error of setState isnt defined.And i want to ask for help.Any help provider will be appreciated.Thank you
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,
),
],
),
);
}
}
this is the Container class
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),
),
),
);
}
}
I tried creating a function with the setState
in it in the State and passed the function to my onPress method and that also didnt work.
2
Answers
AllContainers’ property
onTap
has typeFunction
.But I think your intention is
VoidCallback
type.So, you have to change the type of
onTap
property fromFunction
toVoidCallback
And you have to pass not
onPress()
butonPress
.You should use
final VoidCallback onPress
inside yourAllContainers
instead offinal Function onPress
this is the class you should use to solve your problem.
please note that to use annotations and use camelCase in your coding.
happy coding…