DRing
DRing

Reputation: 7039

Flutter order a list based off reference list

I have a listview with some checkboxtilelist in it. Im trying to maintain the order of the returned selection in the same order as the reference list. Im generating the checkbox list like this:

List<Widget> widgets = [];
for (var o in widget.args.options) {
  widgets.add(
    CheckboxListTile(
      title: Text(o),
      value: widget.args.selections.contains(o),
      onChanged: (v) {
        setState(() {
          v ? selected.add(o) : selected.remove(o);
        });
      },
    ),
  );
}

So for example if the list of options is the standard work week of

['Mon','Tues','Wed','Thurs','Fri','Sat','Sun']

And they select Wed, then Mon, then Fri it currently returns

['Wed','Mon','Fri']

But want it to return

['Mon','Wed','Fri']

Not sure how to go about that, so any help would be appreciated. Thanks

Upvotes: 0

Views: 165

Answers (1)

Ahmed Khattab
Ahmed Khattab

Reputation: 2799

in you case you cant sort alphabetically becuase you have a specific order, so you can try

final all = ['Mon','Tues','Wed','Thurs','Fri','Sat','Sun'];

final selected = ['Wed','Mon','Fri'];

final orderdSelection = all.where((el) => selected.contains(el));

print(orderdSelection ) ///['Mon','Wed','Fri']

Upvotes: 1

Related Questions