0

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?

Vueer
  • 1,432
  • 3
  • 21
  • 57
  • final fields cant be changed. and as method parameters, you send a copy of the object, not the real object. So It will not have any effect on the class variables – meditat Oct 15 '20 at 12:24
  • What you could do, is to pass a callback function to your child widget from your parent, that sets the Guestbook in the parent widget, then the child widget will be built again as the guestbook in the parent changed. – Spanching Oct 15 '20 at 12:47

1 Answers1

0

The reason why the object using guestbook isn't updating after setState() 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 with late or set a default value on the variable to get this working. See more detail here in the docs.

Omatt
  • 8,564
  • 2
  • 42
  • 144