rrousselGit / riverpod

A reactive caching and data-binding framework. Riverpod makes working with asynchronous code a breeze.
https://riverpod.dev
MIT License
6.31k stars 962 forks source link

I getting issue provider not initilized while calling method in build method in AutoDisposeNotifier #3831

Open atulproject99 opened 1 week ago

atulproject99 commented 1 week ago

Describe the bug I have called fetchPost in build method but its give error like provider not initilized.if i add future.delay its working What is best way to call this method and how.

Sample code

import 'dart:developer';

import 'package:action_shortcut_test/services/common/debouncer.dart';
import 'package:action_shortcut_test/services/common/page_state.dart';
import 'package:action_shortcut_test/services/models/post_model.dart';
import 'package:action_shortcut_test/services/remote/api/api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class CustomDropDownNotifier
    extends AutoDisposeNotifier<PageState<List<PostModel>>> {
  late List<GlobalKey> itemKeys;

  @override
  PageState<List<PostModel>> build() {
    fetchPost();
    itemKeys = [];
    return PageInitialState();
  }

  /// Fetch post
  Future<void> fetchPost() async {
    log("fetch initial post");
    state = PageLoadingState();
    final response = await ref.read(apiClient).get(ApiEndpoints.post);

    response.fold((error) {
      state = PageErrorState(error);
    }, (r) {
      final list =
          r.map((e) => PostModel.fromJson(e as Map<String, dynamic>)).toList();
      itemKeys = List.generate(list.length, (index) => GlobalKey());
      state = PageLoadedState(list);
    });
  }

  /// get item keys
  List<GlobalKey> get getItemKeys => itemKeys;

}

final customDropDownProvider = AutoDisposeNotifierProvider<
    CustomDropDownNotifier,
    PageState<List<PostModel>>>(CustomDropDownNotifier.new);

Expected behavior It should not be showing error

YukiAttano commented 4 days ago

I guess you are migrating to the new Notifier, and away from StateNotifier.

If so, check out my Discussion https://github.com/rrousselGit/riverpod/discussions/3836

The problem you are encountering is the following: The StateNotifier created a valid State in its Constructor. The new Notifier does create its first state with build(). In your case, calling 'build() -> fetchPost() -> state' does throw the current exception as you don't have a valid state, your build() method has not finished yet.