Managing flutter navigation with riverpod.

Overview

Navigation for Riverpod

Managing Flutter navigation with riverpod.

Usage

Bootstrap

Replace your root ProviderScope with a RiverpodNavigation widget with your routing hierarchy and give the provided delegate and parser to your MaterialApp.router factory.

  final routes = RouteDefinition(
      template: UriTemplate.parse('/'),
      builder: (context, entry) => MaterialPage(
        child: HomeLayout(),
      ),
      next: [
        RouteDefinition(
          template: UriTemplate.parse('/articles/:id'),
          builder: (context, entry) => MaterialPage(
            child: ArticleLayout(
              id: entry.parameters['id']!,
            ),
          ),
        ),
      ],
    );
    return RiverpodNavigation( // Replaces your root ProviderScope
      routes: routes,
      builder: (context, delegate, parser) => MaterialApp.router(
        title: 'Flutter Demo',
        routerDelegate: delegate,
        routeInformationParser: parser,
      ),
    );

Navigate

From a provider

A navigationProvider is exposed and can be used to read the current navigation state.

To access the underlying notifier that allows various actions, use the navigationProvider.notifier provider.

final myProvider = Provider<MyState>((ref) {
        final navigation = ref.watch(navigationProvider.notifier);
        return MyState(
            navigateToArticles: () {
                navigation.navigate(Uri.parse('/articles'))
            },
            pop: () {
                navigation.pop();
            }
        );
    },
);

From a BuildContext

The notifier can be accessed with the navigation extension method from the BuildContext.

@override
Widget build(BuildContext context) {
    return TextButton(
        child: Text('Articles'),
        onPressed: () {
            context.navigation.navigate(Uri.parse('/articles'))
        }
    );
}

Pop behaviour

To customize the behaviour of pops when navigating back, a PopBehavior callback can be provided to the RiverpodNavigation instance. The result indicates whether the current pop action should be updated, cancelled or auto (default behavior which simply replace the route with the parent one).

 RiverpodNavigation(
    popBehaviour: (notifier, stack) {
        if (stack.lastRoute?.key == Key('share-article')) {
          return PopResult.update(Uri.parse('/'));
        }
        return PopResult.auto();
      },
    // ...
 )

URI rewriting

The uri can be modified before they are processed by the router with the uriRewriter property. This can be useful for redirecting or normalizing uris.

 RiverpodNavigation(
    uriRewriter: (notifier, uri) {
        if (uri == Uri.parse('/home')) {
            return Uri.parse('/');
        }
        const publicPrefix = 'https://example.com';
        final stringUri = uri.toString();
        if (stringUri.startsWith(publicPrefix)) {
            return Uri.parse(stringUri.substring(publicPrefix.length);
        }
        return uri;
    },
    // ...
);
You might also like...

An example of how to mock state for testing widgets when using riverpod StateNotifierProvider

Testing Riverpod StateNotifierProvider An example of how to mock state for testing widgets when using riverpod StateNotifierProvider. These tests work

Dec 13, 2022

template with tests, login flow, riverpod, logging ect.

Flutter Template What to accomplish has tests basic auth flow riverpod as state provider logging (sentry) navigation (I used Beamer last time but migh

Dec 22, 2022

A beautiful navigation bar to use in flutter

A beautiful navigation bar to use in flutter

Beauty Navigation A beautiful navigation bar to use in flutter Inspired from the #dribbble shot by Mauricio Bucardo @m.bucardo Usage Add the Package i

Oct 26, 2021

A library of Flutter to add a new style in the navigation bar.

A library of Flutter to add a new style in the navigation bar.

Navigation Dot Bar Una libreria de Flutter, el cual agrega un BottomNavigationBar con un mejor estilo. Inspirada en la aplicacion "Reflectly" Como usa

Oct 17, 2022

Navigation Screens Project

screens A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if this

Nov 6, 2021

Custom bottom navigation bar with diamond icon in the middle.

Custom bottom navigation bar with diamond icon in the middle.

Pub.dev Scaled List Custom bottom navigation bar with diamond icon in the middle you can customize the number of items either be Five or three. Usage

Dec 21, 2022

Flutter Music Player - First Open Source Flutter based material design music player with audio plugin to play local music files.

Flutter Music Player - First Open Source Flutter based material design music player with audio plugin to play local music files.

Flutter Music Player First Open Source Flutter based Beautiful Material Design Music Player(Online Radio will be added soon.) Demo App Play Store BETA

Jan 8, 2023

a project for learning all Flutter Widgets , sync from flutter.dev the officia website.

Flutter Widgets Catalog (WIP) 计划 1、使用Flutter开发一个全平台的Flutter Widgets Catalog APP,并且开源。在这个APP中可以通过图形化的方式查看所有Widgets的介绍,示例,视频教程。 2、所有文档内容由前一天从flutter.dev

Aug 3, 2022
Comments
  • Cooperation proposal

    Cooperation proposal

    I have prepared a similar project, would cooperation be possible?

    See riverpod_navigator.

    I prepared the package for my new project but my english is bad and I will have little room for maintenance.

    opened by PavelPZ 0
  • allow pages to stop from navigating away, e.g. if there are unsaved state changes

    allow pages to stop from navigating away, e.g. if there are unsaved state changes

    Hello, I am going to start a web project with Flutter, for another project use the Fluro library, however, I could not solve the following problem: If a user is on a page that contains a form and is making modifications is said form, I would like that if he tries to exit without having saved the modifications (either by putting another url, with the browser's backbutton, ...) it would show him an alertdialog giving him the possibility of canceling the navigation to the new url or, on the contrary, of canceling the modifications and staying on the same page where he is. The question is, can I do this with riverpod_navigation? riverpod_navigation has any mechanism by which this functionality can be achieved? Please, if this functionality is possible with riverpod_navigation could you give me some indications. Thank you so much for all the help. Regards, Jose

    opened by Josua2012 0
Owner
Aloïs Deniel
Flutter Freelance
Aloïs Deniel
📓📲 Flutter app for managing study materials in form of photos.

Overview Study Snap is a multi-platform mobile application written with Flutter. Gallery apps are designed for personal everyday photos, kept in timel

Dimitar Petrov 34 Oct 5, 2022
✄ Managing a Fashion designer's daily routine.

TailorMade Managing a Fashion designer's daily routine Built with ❤︎ by jogboms TailorMade is what actually started out as an experiment with Flutter,

Jeremiah Ogbomo 282 Dec 16, 2022
Implementing Firebase Authentication with Riverpod following Flutter Domain Driven Development pattern

firebase_auth_flutter_ddd Firebase authentication example with Hooks Riverpod and Freezed following Flutter DDD architecture Getting Started This proj

Python Hub 42 Jan 8, 2023
Weather App built in Flutter and Riverpod state management

?? Weather App built with Riverpod This is a weather app built using Riverpod as it's State Management. This project is an attempt to rewrite the Weat

Temitope Ajiboye 49 Dec 7, 2022
A playground for me to learn the Riverpod state management library in Flutter.

clothes_shop A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you started if

Benhenneda Majid 2 Oct 25, 2021
Caching with flutter riverpod and looking into future providers. Example to demonstrate stale while revalidate pattern.

FLUTTER SWR EXAMPLE Test stale-while-revalidate pattern with riverpod. Look; query_provider package Backend calls are made with ghibli-api Tested Prov

Dipesh Dulal 7 Jun 30, 2022
Rest API Movie Application built using Flutter and Riverpod

Flickd Flutter Application Flickd Movie Application Flutter Flutter allows you to build beautiful native apps on iOS and Android Platforms from a sing

null 20 Dec 5, 2022
Todo App with Flutter + CleanArchitecture + sqflite + riverpod + state_norifier + freezed!

CleanArchitectureTodoAppTrainingWithFlutter Flutter + CleanArchitecture + sqflite + riverpod + state_notifier + freezed! Motivation I wanted to practi

Ryotaro Oka 75 Dec 16, 2022
Some built-in live templates support developers to use Flutter Riverpod faster on Intellij based

Flutter Riverpod live templates Flutter Riverpod live templates is a way to enhance the way you use Riverpod. It contains a collection of different sn

Minh Tran 27 Dec 16, 2022
Shopping app with riverpod state management

Shopify Shopify admin rest api demo project. We are try to use riverpod as state management to improve widget rebuilding performance. May be at some p

null 35 Nov 19, 2022