Error: A value of type 'Iterable<Transaction>' can't be returned from a function with return type 'List<Transaction>?'. showing this error

Viewed 1594
List<Transaction>? get _recentTransactions {
  return _userTransactions.where((tx) {
    assert(tx != null);
    return tx.date.isAfter(DateTime.now().subtract(Duration(days: 7),),);
  });
 }

when I am doing this it is showing this error can anyone explain

3 Answers

The where function in Dart return you an Iterable<T> and not a List<T>.

But since you have the return type of your function as List<Transaction>, you have to convert the Iterable<Transaction> that you are getting from the where function.

For this use the, toList function on the Iterable.

List<Transaction>? get _recentTransactions {
    return _userTransactions.where((tx) {
        assert(tx != null);
        return tx.date.isAfter(DateTime.now().subtract(Duration(days: 7),),);
    }).toList();
 }

Make a list by .toList

  List<Transaction> get _recentTransactions {
        return _userTransactions.where((tx) {
           
            return tx.date.isAfter(DateTime.now().subtract(Duration(days: 7),),);
        }).toList();
     }

I had a similar issue with Iterable<String>

A value of type 'Iterable<String?>' can't be returned from a function with return type 'Iterable'. I used .cast like that

customerNames.where((String? option) {
          return option!
              .toLowerCase()
              .contains(textEditingValue.text.toLowerCase());
        }).cast()
Related