Home > Back-end >  Get a children childs from List in Flutter
Get a children childs from List in Flutter

Time:12-11

I have problem with getting all childrens from my List in Flutter.

The List structure looks like that:

  • List _mainlist =

    [{element1: [null, "abc1", "abc2"], element2: [null, "abc3", "abc4"], ... }]

My question is how to get List looks like that:

["abc1", "abc2", "abc3", "abc4", ...]

I try with this code but it's not working

List mylist = _mainlist[0];
List alllist = [];

mylist.forEach((element) {
   alllist.add(element);
});

CodePudding user response:

I'm assuming you get a list of lists here, also I'm sure there are better ways of doing this, but at least gets you going until better answer

  var elementList = [
    {
      [null, "abc1", "abc2"],
      [null, "abc3", "abc4"],
    }
  ];

  List allList = [];

  for (final element in elementList) {
    for (final e in element.toList()) {
      allList..addAll(e.where((x) => x != null));
    }
  }
  print(allList.toList());
  //[abc1, abc2, abc3, abc4]

Bear in mind in the future to add you class for better understanding.

CodePudding user response:

If you have a Map instead of a List you can also do:

void main() {
  final _mainlist = [{'element1': [null, "abc1", "abc2"], 'element2': [null, "abc3", "abc4"],}];

  final allElements = _mainlist[0].values;
  final allItems = [];

  for (final element in allElements) {
      allItems.addAll(element.where((item) => item != null));
  }

  print(allItems);

 }

Edit

If you like functions you can also go with

void main() {
  final _mainlist = [{'element1': [null, "abc1", "abc2"], 'element2': [null, "abc3", "abc4"],}];

  final allItems = _mainlist[0].values.reduce((value, element) {
    value.addAll(element);
    return value;
  }).where((item) => item != null).toList();

  print(allItems);

 }
  • Related