Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
atulproject99 opened this issue Nov 12, 2024 · 1 comment
Assignees
Labels
bug Something isn't working needs triage

Comments

@atulproject99
Copy link

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
Copy link

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

If so, check out my Discussion #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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working needs triage
Projects
None yet
Development

No branches or pull requests

3 participants