Home > Blockchain >  Flutter grouped listview by first word
Flutter grouped listview by first word

Time:09-17

I currently have a ListView that displays a large collection of objects. Quite a lot of these objects share the same first one/two words, for example:

  • Peter Johnson
  • Peter Jackson
  • Peter Smith

I would like to split this ListView into groups based on the start of their names. So for example all the Peters would be put in the same group. And then the next name that multiple people share would also be split into their own group.

The problem is that I can't explicitly say what these names are, how would I go about splitting these up?

CodePudding user response:

This is a hard one, I'm going to try to simplify this as much as possible, but the general answer is first write an algorithm that splits your string how you want (in this case, if the first word is the same) and then nest these into a column or whatever.

Here I split the values into a map with the first name as a key and a list of all the people with that first name as a value

// Theres probably a better way to do this
Map<String, List<String>> valuesByFirstName(List<String> values) {
  Map<String, List<String>> result = {};
  for (final val in values) {
    final fn = val.split().first;
    if (result[fn] != null) result[fn]!.add(val);
    else result[fn] = [val];
  }
  return result;
}

Then I'm not sure how you wanna group each of these so I just made some basic example:

var values = valuesByFirstName(originalValues);
return Row(
  children: [
    for (var key in values.keys)
      SizedBox(
        height: 200,
        width: 100,
        child: ListView(
          children: [
            Text(key, style: TextStyle(fontSize: 20)),
            for (var value in values[key])
              Text(value),
          ]
        ),
      ),
    ),
  ],
);

If what you want is to contract the different sections, take a look at the ExpansionPanel widget

  • Related