Skip to content

Document an autocomplete use-case #4067

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

Open
Zverik opened this issue Apr 18, 2025 · 0 comments
Open

Document an autocomplete use-case #4067

Zverik opened this issue Apr 18, 2025 · 0 comments
Assignees
Labels
documentation Improvements or additions to documentation needs triage

Comments

@Zverik
Copy link

Zverik commented Apr 18, 2025

First documented in #4066.

Imagine a search field with autocompletion. The value in the field is stored in a state variable. It is then passed to a FutureProvider.family, which requests a list of results. Alas, when a search string changes, it builds a new provider, which has its loading state. Resulting in a loading screen after every keypress.

Given this might be a pretty common case for a family provider, I think it might need to be explicitly documented, like for debouncing, so that other people don't fall into the trap of the loading state.

Here is a sample code:

final autocompleteProvider = FutureProvider.autoDispose
    .family<AutocompleteResults?, String>((ref, value) async {
  if (value.length < 2) {
    return null;
  }

  bool stop = false;
  ref.onDispose(() {
    stop = true;
  });

  await Future.delayed(Duration(milliseconds: 500));
  if (stop) return null;

  return await SomeClass.fetchData(value);
}

class _PageState extends ConsumerState<Page> {
  String _lookingFor = '';

  @override
  Widget build(BuildContext context) {
    final found = ref.watch(autocompleteProvider(_lookingFor));

    return Column(
          children: [
            Expanded(child: found.valueOrNull == null ? EmptyPage() : ResultsPage(found.value!)),
            WordSearchBar(
              onUpdateWord: (value) {
                setState(() {
                  _lookingFor = value;
                });
              },
            ),
          ],
        );
  }
}

There are ways to circumvent this: abandon the provider altogether, use a non-family provider with a side effect, create a new family provider for the page, not for the search, or cache search results in the page state. Each of those has their drawbacks, the main being, they don't feel very "riverpod".

So, it might need to be solved in the library, or a circumvention method documented.

@Zverik Zverik added documentation Improvements or additions to documentation needs triage labels Apr 18, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation needs triage
Projects
None yet
Development

No branches or pull requests

2 participants