Home > Software engineering >  How can I filter an Flutter List based on a field with an array value?
How can I filter an Flutter List based on a field with an array value?

Time:06-21

I am building an app on Flutter with a Firebase backend and I am stuck on querying a List where the value of a field is an array.

The documents are fetched from Firestore and mapped into a data model:

    class HItemsData {
     final bool attachment;
     final String body;
     final bool mandatory;
     final String title;
     final List position;

  HItemsData({
    required this.attachment,
    required this.body,
    required this.mandatory,
    required this.title,
    required this.position,

  });
}

I get the items into my widget:

final hItems = Provider.of<List<HItemsData>?>(context);

A simple filter would be:

    final data = hItems?.where((el) => el.mandatory == true).toList();

However, I would like to filter the List that I get from Firestore based on the position field.

The position looks something like the data sets below and I would like to return List of items for every document in which the position contains a certain value, like '1'. in the below, I should get "The First, and The Third"

attachment: true,
body: "The First",
mandatory: true,
position: ['1', '2', '3', '5'],
title: "One"

attachment: true,
body: "The Second",
mandatory: true,
position: ['9', '7', '3', '5'],
title: "Two"

attachment: false,
body: "The Third",
mandatory: true,
position: ['4', '3', '1', '5'],
title: "Three"

Please help.

Thanks.

CodePudding user response:

final data = hItems?.where((el) => el.position.contains('1')).toList();

I think this should do it. It iterates through the position array elements and returns a true if it finds '1' in the array.

CodePudding user response:

final data = hItems?.where((el) => (el['position'].indexOf('1')>=0).toList();

You can check indexOf in a list and if an element is present it will return an index or else it will return -1.

  • Related