2

I have a scenario, where I want to change state of loading class while I load my data on screen. So for that I am trying to switch the initial state of a provider from another provider but throws me an error. "Providers are not allowed to modify other providers during their initialisation." I need to know the very best practice to handle this kind of scenarios. My

classes are as follow:

class CleansingServices extends StateNotifier<List<CleansingBaseModel>> {
  CleansingServices() : super([]);

  void setServices(List<CleansingBaseModel> data) {
    state = data;
  }
}

final cleansingServicesProvider = StateNotifierProvider<CleansingServices, List<CleansingBaseModel>>((ref) {
  final data = ref.watch(loadServicesProvider);
  final dataLoading = ref.watch(cleansingLoadingStateProvider.notifier);

  data.when(
    data: (data) {
      ref.notifier.setServices(data);
      dataLoading.setNotLoading();
    },
    error: (error, str) {
      dataLoading.setNotLoadingWithError(error);
    },
    loading: () {
      dataLoading.setLoading();
    },
  );
  return CleansingServices();
});

Naveed Ullah
  • 129
  • 7
  • you can't do that..that is not how to use a provider. the `.when` property is meant to render a ui and not to mutate any other stuff. – john Oct 31 '22 at 06:57
  • @john I understand. This is just an example. For example in this provider I change state of another provider it doest not allow me. How would you do that? – Naveed Ullah Oct 31 '22 at 09:04
  • That's the thing: You don't. It's not allowed. You should find an alternate solution to the true problem you're trying to solve. But with the way the question is formulated, we can't really help you. – Rémi Rousselet Oct 31 '22 at 10:14
  • @RémiRousselet thanks for your reply. For example, I want to load the services from server as soon my screen is launched. But until it's not loaded I want to trigger the loading state of another state notifier. What is the recommended way for that? – Naveed Ullah Oct 31 '22 at 10:55

1 Answers1

1
     class CleansingServices extends StateNotifier<List<CleansingBaseModel>> {
      var data ; 
      CleansingServices(this.data) : super([]){

      data.when(
        data: (data) {
          ref.notifier.setServices(data);
          dataLoading.setNotLoading();
        },
        error: (error, str) {
          dataLoading.setNotLoadingWithError(error);
        },
        loading: () {
          dataLoading.setLoading();
        },
      );

    }
    
      void setServices(List<CleansingBaseModel> data) {
        state = data;
      }
    }
    
    final cleansingServicesProvider = StateNotifierProvider<CleansingServices, List<CleansingBaseModel>>((ref) {
      final data = ref.watch(loadServicesProvider);
      final dataLoading = ref.watch(cleansingLoadingStateProvider.notifier);
    
     
      return CleansingServices(data );
    });
Erfan Eghterafi
  • 4,344
  • 1
  • 33
  • 44