How can a provider shared on multiple pages update only the current page?

Viewed 55

I have an app with multiple pages and a filter that is shared on all of them. When the filter is changed it triggers an update on all the pages.

As an example this are the providers that use the same filter (filterProvider):

final provider1 = FutureProvider<List<...>>((ref) async {
  final String filter = ref.watch(filterProvider);
  return ref.read(apiProvider).getFirstPageData(filter);
});

final provider2 = FutureProvider<List<...>>((ref) async {
  final String filter = ref.watch(filterProvider);
  return ref.read(apiProvider).getSecondPageData(filter);
});

This is the page that navigates to the second one:

class FirstPage extends StatelessWidget {
  const FirstPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final data = ref.watch(provider1);

    return Scaffold(
      appBar: AppBar(),
      body: Column(
        children: [
          const Filter(), // This widget uses filterProvider
          data.when(...),
          ElevatedButton(
            child: Text('Navigate'),
            onPressed: () => Navigator.of(context).push(MaterialPageRoute(
          builder: (context) => SecondPage(),
            )),
          ),
        ],
      ),
    );
  }
}

And the second page which is also using the same filter:

class SecondPage extends StatelessWidget {
  const SecondPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final data = ref.watch(provider2);

    return Scaffold(
      appBar: AppBar(),
      body: Column(
      children: [
        const Filter(), // This widget uses filterProvider
        data.when(...),
      ]),
    );
  }
}

When the filter is updated, how can I trigger a change only for the current page (top of the navigator stack)?

I tried to use pushReplacement instead of push (as recommended here) and it works as expected but we lose the reference to the previous page, so we have to manually implement a back button which adds a lot of complexity.

Thanks.

0 Answers
Related