Compared to my previous question I managed to use the "points" variable but when I try to use it in a method it gives me a value of 0 and not that of the points
the method in the CartModel
int calculateTotal() {
int totalPrice = 0;
for (int i = 0; i < cartItems.length; i++) {
totalPrice += int.parse(cartItems[i][1].toString());
}
return totalPrice;
}
PointsState pointsstate = pointsState();
void myMethod() {
int punti = pointsstate.points;
int total = calculateTotal();
if (punti >= total) {
punti -= total;
pointsstate.points = punti;
}
}
Pointspage
class points extends StatefulWidget {
pointsState createState() => pointsState();
}
class pointsState extends State<points> {
int points = 0;
int get getPunti {
return points;
}
String cardHolderName = '';
@override
void initState() {
super.initState();
_loadPunti();
}
_loadPunti() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
points = (prefs.getInt('points') ?? 0);
});
}
_savePunti() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setInt('points', points);
}
@override
Widget build(BuildContext context) {
Device.screenType == ScreenType.tablet;
return SizedBox(
width: 100.w,
height: 100.5.h,
child: SizedBox(
width: 100.w,
height: 20.5.h,
child: Scaffold(
appBar: AppBar(
backgroundColor: Colors.transparent,
elevation: 0,
centerTitle: false,
),
OutlinedButton.icon(
label: Text('ricevi',
style: GoogleFonts.notoSerif(
fontWeight: FontWeight.bold)),
icon: Icon(
Icons.money,
color: Colors.green[200],
),
style: OutlinedButton.styleFrom(
primary: Colors.white,
backgroundColor: Colors.blueGrey[900]),
onPressed: () async {
await Future.delayed(
Duration(seconds: 60)); // attendi 1 minuto
setState(() {
punti += 3;
});
_savePunti();
},
),
],
),
),
),
],
),
),
),
),
);
}
}
the points variable when used in mymethod is taken as a value of 0 but in reality it should have the value updated after each setstate in the parent class i.e. PointsPage