Flutter Riverpod StateNotifier initialize state is empty but whenever buildMethod rebuild it's not empty

Viewed 95

I got a HiveBox and I want to access it with Riverpod StateNotifier.

This is how I defined this provider: final hiveSalonProvider = StateNotifierProvider<HiveSalonNotifier, List>((ref) { return HiveSalonNotifier(); });

Then i created a StateNotifier class which it's listening to list of SalonModel class.

class HiveSalonNotifier extends StateNotifier<List<SalonModel>> {
  HiveSalonNotifier([List<SalonModel>? state])
      : super(state ?? <SalonModel>[]) {
    _cacheManager = SalonCacheManager('boxB');
    fetchDatasFromHiveBox();
  }

  late final CacheManagerBase<SalonModel> _cacheManager;
  List<SalonModel>? salonItems = [];

  Future<void> fetchDatasFromHiveBox() async {
    await _cacheManager.init();
    if (_cacheManager.getValues()?.isNotEmpty ?? false) {
      state = _cacheManager.getValues()!;
      salonItems?.addAll(state);
      
      print('provider: datas from caches');
    } else {
  
      print('provider:provider: datas from services');
    }
  }

It seems there is no error. I think so there is not. But in UI (StatelessWidget);

In build method, I have defined our provider:

var hive = ref.read(hiveSalonProvider.notifier);

In Column:

(hive.salonItems?.isNotEmpty ?? false)
                  ? ListView.builder(
                      shrinkWrap: true,
                      itemCount: hive.salonItems?.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          leading: const CircleAvatar(),
                          title: Text(
                              '${hive.salonItems?[index].salonName.toString()}'),
                        );
                      },
                    )
                  : const CircularProgressIndicator(color: Colors.white),

At first hot reload, this widget showing me CircularProgressIndicator. But then I press the save code combination from keyboard (CTRL+S in vscode), it's showing listView correctly. Where is the problem ?

0 Answers
Related