Home > Enterprise >  RetainWhere Function Dart Uncertanties
RetainWhere Function Dart Uncertanties

Time:10-02

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.

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

CodePudding user response:

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

  • Related