Cannot set selected items with future
I have tried selectWhere function using MultiSelectController in initState, but it is not setting values. I think new function must be added like setItems, setItem, addItem, addItems. In this scenario We can just give the values before future is called!
@Abdulvaliy
1. Create the MultiSelect Controller
First, create a controller for the multi-select dropdown that will manage the selected items:
final controller = MultiSelectController<YourEntityClass>();
2. Use Bloc/Provider for State Management You can use any state management package like Bloc or Provider to manage the state of your selected and fetched items. In this example, we're using Bloc.
Ensure you maintain two lists in your Bloc state:
selectedItemsList: The list of preselected items. fetchedItemsList: The list of all fetched items for the dropdown.
3. BlocConsumer Listener
In your BlocConsumer widget, use the listener method to set the preselected items in the dropdown. This will allow you to set the selected items once the state is loaded.
listener: (context, state) { if (state is StateLoaded) { // Select the preselected items by matching IDs controller.selectWhere( (item) => state.selectedItemsList ?.any((selectedItem) => selectedItem.id == item.value.id) ?? false, ); } },
Here’s what’s happening: state.selectedItemsList: The list of items that should be preselected. controller.selectWhere: The method used to mark items as selected in the dropdown. The condition (selectedItem.id == item.value.id) checks whether each fetched item matches an item in the selectedItemsList.
4. Pass the Controller to the Dropdown When building your MultiDropdown widget, pass the controller as a parameter to bind the selected items.
MultiDropdown<YourEntityClass>( controller: controller, )
I faced the similar issue with setting preselected items in a multi-select dropdown using a MultiSelectController. It wasn’t working as expected when trying to use the selectWhere function in the initState. After some troubleshooting, I found this solution that might help you also.