How to filter a list of obseravble in rxdart
Asked Answered
B

1

6

I am trying to implement bloc pattern in rxdart . I am trying to build todo app type of app . I implemented showing all items in list but what I want is not to show completed and uncompleted items in different part . However I am not able to filter the items based on completed on rxdart .

import 'package:rxdart/rxdart.dart';
import '../models/ShoppingItem.dart';
class ShoppingItemBloc {
  final _shoppingItems = BehaviorSubject<List<ShoppingItem>> 
(seedValue: []);

Observable<List<ShoppingItem>> get allShoppingItems => 
_shoppingItems.stream;

 //Getter to implement
 Observable<List<ShoppingItem>> get completedShoppingItems =>

 dispose() {
  _shoppingItems.close();
 }
}

What I wanted is to get the completed shoppingItems . The class ShoppingItem has a boolean property completed . I wanted to filter it on that basis .

Any help would be appricated thanks

Byler answered 3/2, 2019 at 5:44 Comment(0)
D
12

you can use where on the stream to filter out as per your need. Since you are observing list of item you need to map before filtering individual item. In our case it would be something like this.

 Observable<List<ShoppingItem>> get completedShoppingItems => 
    _shoppingItems.stream.map((itemList) =>
        itemList.where((item) => item.completed));
Divertimento answered 3/2, 2019 at 7:8 Comment(3)
You need to put .toList() at lastByler
Is it possible to return a single item where condition is met?Leroylerwick
yes you can. just use firstWhere instead of where. This will return the first item that satisfies the condition. for more read api.dart.dev/stable/2.9.3/dart-core/Iterable/firstWhere.htmlDivertimento

© 2022 - 2024 — McMap. All rights reserved.