I try to update an object in Flutter from a child widget. The object which I want to update was passed as param to the child. The problem: The object does not want to change. I work on a Stateful widget and update the state with setState
, but nothing changes. Maybe you can find an error in my code.
My object
final guestbook = Guestbook({
title: "Test"
// ... some other parameters
})
The function where I pass the Guestbook
object to the child widget
void _editGuestbook(Guestbook guestbook, BuildContext context) {
CupertinoScaffold.showCupertinoModalBottomSheet(
context: context,
builder: (BuildContext context, ScrollController scrollController) {
return EditGuestbook(
guestbook: guestbook, // Here I pass the object to the child
scrollController: scrollController,
);
}).then((value) {
setState(() {
guestbook = value;
});
});
}
On the next widget, I update some values in the database and want to change also my local object, so that the user can see that the updating was successfull. Therefore I pass the object with the updated values as argument back to the parent view.
final Guestbook guestbook;
......
........
// Update database
final gb = widget.guestbook;
setState(() {
updatedGuestbook = Guestbook(
title: "New title",
// ... some other parameters
});
await GuestbooksDatabase()
.updateGuestbook(guestbook: updatedGuestbook, key: gb.id)
.then((_) {
Get.back(result: updatedGuestbook); // Here I send data back to parent
});
And as you can see above after retrieving the new object I update the state with setState
:
setState(() {
guestbook = value;
});
Bot nothing changes in the view. I always see the old state. If I pull to refresh to load the new entries directly from the database it updates. Is there a way to simply update the local object so that I don't need the additional server request?
The reason why the object using
guestbook
isn't updating aftersetState()
is because guestbook was set to final. As of this writing, in Flutter 3.7.8 should give out a warning that the value can't be used as a setter since the value is final. You can either lazily initialize the variable withlate
or set a default value on the variable to get this working. See more detail here in the docs.