Home > Software engineering >  Riverpod Flutter: Looking for best way to combine FutureProvider with StateNotifierProvider
Riverpod Flutter: Looking for best way to combine FutureProvider with StateNotifierProvider

Time:04-21

I am working on a basic Support Ticket System. I get the Tickets from Firebase (Either as a Stream or Future). I want to allow some Filtering Options (e.g. sort by Status and Category). For this, I thought about using A Future Provider to get the List and a StateNotiferProvider to update the List depending on which filter is being used. This is the code I have so far:

final ticketListStreamProvider =
    RP.FutureProvider((_) => FirestoreService.getTicketList());


class TicketListNotifier extends RP.StateNotifier<List<Ticket>> {
  TicketListNotifier() : super([]);

  void addTicket(Ticket ticket) {
    state = List.from(state)..add(ticket);
  }

  void removeTicket(Ticket ticket) {
    state = List.from(state)..remove(ticket);
  }
}

final ticketsController =
    RP.StateNotifierProvider<TicketListNotifier, List<Ticket>>(
  (ref) => TicketListNotifier(),
);

There are multiple issues I have with that. Firstly it doesn't work. The StateNotifier accepts a List and not a Future<List>. I need to convert it somehow or rewrite the StateNotifier to accept the Future. I was trying to stay close to one of the official examples. (https://github.com/rrousselGit/riverpod/tree/master/examples/todos) Unfortunately, they don't use data from an outside source like firebase to do it.

What's the best approach to get resolve this issue with which combination of providers?

Thanks

CodePudding user response:

  1. You can fetch your ticketlist in your TicketListNotifier and set its state with your ticket list.
class TicketListNotifier extends RP.StateNotifier<List<Ticket>> {
  TicketListNotifier() : super([]);

  Future<void> fetchTicketList() async {
    FirestoreService.getTicketList().when(
       //success
       // state = fetched_data_from_firestore
       // error
       // error handle
    )
  }
}

final ticketsController =
    RP.StateNotifierProvider<TicketListNotifier, List<Ticket>>(
  (ref) => TicketListNotifier(),
);

  1. Call this method where you want to fetch it /*maybe in your widget's initState method
ref.read(ticketsController.notifier).fetchTicketList();

Now ref.read(ticketsController); will return your ticket list

  1. Since you have the ticket list in your TicketListNotifier's state you can use your add/remove method like this:
ref.read(ticketsController.notifier).addTicket(someTicket);
  • Related