String title = '';
child: GestureDetector(
onTap: () {
setState(
() {
final docRef = FirebaseFirestore.instance
.collection('CIPsubmit')
.doc(wee)
.get()
.then(
(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
final title = data['title'];
print(title.toString());
},
);
},
);
},
I am getting a string from firebase, and have put it in a setState to change a text value. The print shows that String title has updated to the right value, but the text is not changing.
CodePudding user response:
It is not a good idea to put an asynchronous function, because the time when setState
update the widget tree is NOT when the string is updated.
The fix is also simple:
onTap: () async /* NOTE: mark the anonymous function as asynchronous */ {
final docRef = await FirebaseFirestore.instance
.collection('CIPsubmit')
.doc(wee)
.get();
final data = docRef.data() as Map<String, dynamic>;
final title = data['title'];
setState(() { print(title.toString();})
print(title.toString());
},
);
},
);
CodePudding user response:
First of all, title variable above GestureDetector is not the same with title inside that code
(DocumentSnapshot doc) {
final data = doc.data() as Map<String, dynamic>;
final title = data['title'];//with this. Instead you need to write below line code
// title = data['title'];
print(title.toString());
},
Secondly, it seems very bad wrapping whole code in onTap with setState. You need to just wrap line, which you change title variable value.
setState((){
title = data['title'];
});
And finally, a title variable(it is preferred declare all variables in State class out of build method) should be declared out of build method.