Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TextFormField not resetting its Initial Value

I'm somewhat new to Flutter so I don't know if this is the "correct" way of updating data collected from a server. In my case, what I'm doing is (my app code is quite long, I think the description below will suffice):

  1. Let the user create a custom form for a given date.
  2. Have him upload the data to a server (more specifically, Firebase).
  3. If he clicks on a date, the form should be updated to the most recent one saved on Firebase.
    • To do this, I'm deleting all of the TextFormField widgets (they are held in a Map which I reset with widgetsMap = {}, which is also what I do for the form data itself) and rebuilding them with the data retrieved from Firebase.
    • The TextFormField should have an initial value based on what was retrieved from Firebase. To achieve this, I've tried to use a controller and an initialValue, but neither have worked.
      • The problem is that, if I want to update the initial value of a field a second time, the previous one will remain. For example, if date 1 has an initial value of Hello and date 2 has an initial value of World; when I click on date 2 coming from date 1, although the TextFormField widgets (there might even be a different number of them) will be built correctly, the initial value shown will still be Hello.

So what is happening? Shouldn't the initialValue of a widget be wiped out once the widget and the data have been reset? Do those objects still exist in the background somewhere even after I have reset them with = {} (I thought that, since dart is a garbage-collected language, these objects would be deleted once the references to them disappear...)?

like image 618
Philippe Fanaro Avatar asked Jan 01 '23 12:01

Philippe Fanaro


1 Answers

Add Key to TextFormField. You can use Key(initialValue). For example:

TextFormField(
  key: Key(widget.initialValue),
  initialValue: widget.initialValue),
  ...
)

Although you reset your own map of TextFormFields, if you put new TextFormFields in same position in the widget tree, the Flutter framework will reuse the previous state. Setting the Key will tell Flutter that this is a different widget.

like image 161
Filip P. Avatar answered Jan 08 '23 04:01

Filip P.