I've got an error while i tried to add value to value from firestore. I want to sum value from kcal variable with firestore "progress" value
progressAdd = nutr kcal2;
Future addMeal() async {
var nutr;
await FirebaseFirestore.instance
.collection('usersData')
.doc(FirebaseAuth.instance.currentUser!.uid)
.get()
.then((doc) => {nutr = doc.data()});
print('test');
if (nutr != null) {
this.progress = nutr['progress'];
setState(() {
progressAdd = nutr kcal2;
FirebaseFirestore.instance
.collection('usersData')
.doc(FirebaseAuth.instance.currentUser!.uid)
.update({'progress': progressAdd});
});
} else {
print('test2');
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
backgroundColor: mainFontColor().tsubColor,
title: Text(
':/',
textAlign: TextAlign.center,
style: GoogleFonts.lato(
fontWeight: FontWeight.w600, color: Colors.white),
),
content: Container(
height: 120,
width: 250,
child: Column(children: [
Text(
'Something went wrong!',
style: GoogleFonts.dosis(color: Colors.white),
),
SizedBox(
height: 5,
),
Text(
'Go back and try again!',
style: GoogleFonts.dosis(color: Colors.white),
),
SizedBox(
height: 20,
),
Container(
height: 40,
width: 180,
child: ElevatedButton(
child: Text('OK'),
style: ElevatedButton.styleFrom(
backgroundColor: mainFontColor().tsubColor2),
onPressed: (() => Navigator.pop(context))),
)
]),
),
);
});
}
}
CodePudding user response:
This line: .then((doc) => {nutr = doc.data()});
will assign the doc.data()
which have a type of Map<String, dynamic>
to the nutr
variable.
so, this:
progressAdd = nutr kcal2;
is actually not valid, because you want to make an addition over objects that can't be summed, nutr
have a type of Map<String, dynamic>
and kcal2
is double
.
from the code I read, I assume that you want to get the existing progress on the Firestore document and update it with the sum of it kcal2
, so try the following:
instead of:
progressAdd = nutr kcal2;
replace with this:
progressAdd = this.progress kcal2;
this now should be valid that you want to sum to numbers the update in Firestore.