Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RetainWhere Function Dart Uncertanties

I have a following code.

void onItemSelected(String status) {
    print("default list count: " + transactionList.length.toString());
    List<trx.Transaction> filteredTrx = transactionList;
    
    print("default2 list count: " + transactionList.length.toString());
    filteredTrx.retainWhere((element) => element.status == status);
    print("default3 list count: " + transactionList.length.toString());

    
    filteredTransactionList = filteredTrx;
  }

I am doing a dropdownbutton to allow user to filter based on their status selection. In this example, the status of the transaction can be (processing, approved, rejected).

I know that I can use foreach loop to compare and assign into a new list. But i would like to use a function which is more efficient. And i think that retainWhere could be a good solution for it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So, I had a list of Transactions recorded into transactionList variable. And to prevent this list from changing, i declare a new list to store into it and apply it with retainWhere function. However, i noticed that once it runs the retainWhere function, the default transactionList will be empty as well. Does anyone know why?

The debug result is as below:

I/flutter (12068): default list count: 2
I/flutter (12068): default2 list count: 2
I/flutter (12068): default3 list count: 0

>Solution :

You are not copying the list, you are copying the reference to same list (see the second sentence here: https://dart.dev/guides/language/language-tour#variables). This is the reason why both lists are affected by retainWhere.

You probably want to (shallow) copy the list like this:

List<trx.Transaction> filteredTrx = List.from(transactionList)

https://api.dart.dev/stable/2.18.0/dart-core/List/List.from.html

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading