stacked
stacked copied to clipboard
[bug]: Setting Dynamic Default Form Values Does Not Work
Describe the bug
I am using a form view widget in stacked. I would like to dynamically set the initial value of a text field based on the props passed to the component, thus I cannot use the initialValue
property inside the FormView
decorator. My current approach is to accept an object containing the form values inside of my constructor of the view model and set the form values. However, this does not updating my text fields with the correct values.
To reproduce
Inside of my form's view model's constructor, I'm accepting the object containing the form's values and setting those.
SetTourInfoModel(Tour tour) {
titleValue = tour.title;
descriptionValue = tour.description;
rebuildUi(); // not sure if this is necessary but included it for the sake of completeness.
}
and I call this function inside the widget like:
@override
SetTourInfoModel viewModelBuilder(
BuildContext context,
) =>
SetTourInfoModel(initialTour); // where initialTour is a variable passed into widget's constructor
Expected behavior
This should set the form's text field values to be the ones described in the Tour
object I'm passing to my view model.
Screenshots
No response
Additional Context
No response
This was user error. Instead of setting the values in the view model's constructor I'm calling an initFormValues
inside the onViewModelReady
function and setting the form values there. It might be helpful to document this process on the docs as the existing docs on forms is extremely simplistic. I look forward to the "deep dive of Stacked Forms" coming soon!
I still can't seem to get forms with initial values working. I'm calling my initValues in my form model like the following:
@override
void onViewModelReady(SetTourInfoModel viewModel) {
syncFormWithViewModel(viewModel);
viewModel.initFormValues();
}
If I open the widget that uses the form, edit it, close it, then open it again I get the following error:
setState() or markNeedsBuild() called during build.
With the stack trace leading to my viewModel.initFormValues()
call. For reference, here is that function inside the view model:
initFormValues() {
titleValue = _initialTour?.title;
descriptionValue = _initialTour?.description;
}
You should call initFormValues
on a postFrameCallback
just to be safe.
It's trying to rebuild the tree while it's rebuilding.