1

I am wondering when/where to perform operations after HTTP request done with a RESTFUL API. I am using a StateNotifdier as a mean of Controller to perform simple CRUD operations such as retrieveItems, addItem, updateItem and deleteItem.

I would need to sort, group, filter and take the last n items for instance for my UI as I have to show some stats for the current day, the current week, display the items list for the month. This kind of UI dashboard actually. Where to code those from your opinion? Do I need to create a new provider for each of these operations?


final itemListControllerProvider = StateNotifierProvider<
    ItemListController, AsyncValue<List<Item>>>((ref) {
  return ItemListController(ref.read);
});

class ItemListController
    extends StateNotifier<AsyncValue<List<Item>>> {
  final Reader _read;

  ItemListController(this._read) : super(AsyncValue.loading());

  Future<void> retrieveItems({required type, bool isRefreshing = false}) async {
     try {
        final items = await _read(itemRepositoryProvider).getData(type: type);    
        state = Async.data(items);
     } catch (e) {
     }
  }

  Future<void> addItem({required type, dynamic data}) async {
     try {
        final item = await _read(itemRepositoryProvider).addData(type: type, data: data);    
        state.whenData((items) => state=Async.data(items..add(item)) );
     } catch (e) {
     }
  }

  Future<void> updateItem({required type, dynamic data}) async {
  }
 
  Future<void> deleteItem({required type, dynamic data}) async {
  }
}

Chris
  • 31
  • 3

1 Answers1

0

Do I need to create a new provider for each of these operations?

Short answer: No!

You can just add methods for each operation and get the data to be sorted on them, for example:

Class ItemListController
    extends StateNotifier<AsyncValue<List<Item>>> { 
  ...

  Future<void> sortList({ List<Item> list }) {
    final _sortedList = list.reverse();

    state = ItemListState.sorted(_sortedList);
  }

  ​Future<void> groupList({ List<Item> list }) {
    ​final _groupedList = list.filter((item) => true);

    ​state = ItemListState.grouped(_groupedList);
  ​}
}

Creating a new provider for each of these operations just add unnecessary complexity to your code, keep it simple unless you find that this change is necessary.

Eleandro Duzentos
  • 1,370
  • 18
  • 36