I'm building a flutter app with a number of drop down lists using flutter_form_builder. On occasion I get an error saying that the initial value is not in the drop down list. This could happen for several reasons such as a person being set to inactive or deleted because they left and no longer appearing in the list. This problem causes a flutter crash.
How can I check the incoming list for the value and then reset it to 0 if not in the list. Preferably, I'd like to ignore the error completely as there is no problem with this condition in many cases and the user can reset the selection. I presume I need to do this the hard way and iterate through the selection array and check against the initial value.
Here is a drop down I'd like to protect from this error. In this case the author_id is the user_id and has a left join in the select query so the view will always work. The user_id may not be in the incoming drop down choices.
FormBuilderDropdown(
name: 'author_id',
initialValue: quote.authorId == 0 ? null : quote.authorId,
decoration: const InputDecoration(
labelText: "Author",
hintText: 'Select an Author',
contentPadding: EdgeInsets.all(16),
focusedBorder: OutlineInputBorder(
borderSide: BorderSide(),
),
border: OutlineInputBorder(
borderSide: BorderSide(),
),
),
items: List<DropdownMenuItem>.generate(
authors.authors.length,
(index) {
return DropdownMenuItem(
value: authors.authors[index].authorId,
child: Text(
authors.authors[index].fullName,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
);
},
growable: false,
),
validator: FormBuilderValidators.compose(
[
FormBuilderValidators.required(),
],
),
),
I was hoping for a property in the widget like a
dontExplodeOnMemberMissingswitch but this is what learned from FlutterFormBuilderDropDowncrashes.The initial value must be in the selection list. There's no event to trap for this so we need to do some defensive coding.
The formBuilderDropDown will ignore null as an initial value. The most common case for value not being in the selection list is when it's at a default 0 or if the previous selection has been removed from the selection candidates.
The workaround is to test the initial value against the selection values before navigating to the update page.
First, we need a function to check the selection vales.
Now, in an
onPressedbutton function we call the code and set the initial value to 0 if it isn't.Finally, in out update form we test the initial value and return null with a ternary function if it is. The drop down will always ignore null.
And in the form validation we only update the author_id field if the value is not null as it cause an error expecting int but got null. The initial value will remain as either 0 or it's previous setting as the data provider or author instance has not been updated from it's original value. The value will only be changed if the user selects a value from the drop down selections.