Code Monkey home page Code Monkey logo

page_router's Introduction

page_router

Experimental router for Flutter built using the Navigator 2.0 API.

Usage

class _PageRouterExampleState extends State<PageRouterExample> {
  final routerData = PageRouterData({
    '/': RoutePath(
      builder: (context, params) => FadeTransitionPage(
        key: ValueKey('/'),
        child: HomeScreen(),
      ),
    ),
    '/users/:id': RoutePath(
      validator: idValidator,
      builder: (context, params) => MaterialPage(
        key: ValueKey('/users/:id'),
        child: UserScreen(userId: params[':id']),
      ),
    ),
    '/users/:id/preferences': RoutePath(
      validator: idValidator,
      builder: (context, params) => FadeTransitionPage(
        key: ValueKey('/users/:id/preferences'),
        child: UserPreferencesScreen(
          userId: params[':id'],
        ),
      ),
    ),
  });

  Validator idValidator = (params) async {
    var id = int.tryParse(params[':id']);
    return id != null && id < 100;
  };

  @override
  Widget build(BuildContext context) {
    return PageRouter(
      data: routerData,
      child: MaterialApp.router(
        title: 'page_router Example App',
        routerDelegate: routerData.routerDelegate,
        routeInformationParser: routerData.informationParser,
      ),
    );
  }
}
OutlinedButton(
  child: Text('Go to User 123'),
  onPressed: () {
    PageRouter.of(context).pushNamed('/users/123');
  },
),

See the example/ application for a complete example

Known Issues / Unsupported features

  • Hierarchical Routing (see section below)
  • Displaying subroutes on the same screen
  • Validation
  • Including pages on the stack

Issue: Hierarchical Routing

Right now, this package requires each route to be defined up-front:

  final routerData = PageRouterData({
    '/': RoutePath(
      builder: (context, params) => FadeTransitionPage(
        key: ValueKey('/'),
        child: HomeScreen(),
      ),
    ),
    '/users/:id': RoutePath(
      builder: (context, params) => MaterialPage(
        key: ValueKey('/users/:id'),
        child: UserScreen(userId: params[':id']),
      ),
    ),
    '/users/:id/preferences': RoutePath(
      builder: (context, params) => FadeTransitionPage(
        key: ValueKey('/users/:id/preferences'),
        child: UserPreferencesScreen(
          userId: params[':id'],
        ),
      ),
    ),
  });

Sometimes, parts of the app are built separately, with separate routes. For example, Team A might define routes for the app, but rely on Team B to define routes for a part of the app.

To support this use-case, a routing package can add support for hierarchical routing. For example:

library app;
import 'team_b.dart';

var routerData = PageRouterData({
  '/': RoutePath(
    builder: (context, params) => MaterialPage(
      child: Scaffold(
        body: Center(
          child: Text('home screen'),
        ),
      ),
    ),
    subroutes: {
      '/teamB': teamBRoutePath,
    },
  ),
});
library team_b;

var teamBRoutePath = RoutePath(
  builder: (context, params) => MaterialPage(
    child: Scaffold(
      body: Center(
        child: Text("Team B's widget"),
      ),
    ),
  ),
  subroutes: {
    '/details': RoutePath(
      builder: (context, params, child) {
        return MaterialPage(
          child: Scaffold(
            body: Center(
              child: Text('details screen'),
            ),
          ),
        );
      },
    ),
  },
);

The entrypoint for an app needs to decide how to structure the subroutes for an app, but leaves the underlying route structure to the library / package being imported.

Issue: Displaying subroutes on the same screen

Some apps may need to display the child. In this example, both the "My App" Text widget and the "Details" Text widget are displayed in the Column when the app navigates to '/details':

library app;

var routerData = PageRouterData.hierarchical({
  '/': RoutePath(
    childBuilder: (context, params, child) => MaterialPage(
      child: Scaffold(
        body: Column(
          children: [
            Text('My App'),
            child,
          ],
        ),
      ),
    ),
    subroutes: {
      '/details': RoutePath(
        builder: (context, params) {
          return MaterialPage(
            child: Scaffold(
              body: Center(
                child: Text('Details'),
              ),
            ),
          );
        },
      ),
    },
  ),
});

Issue: Validation

Before a route is navigated to, the app may choose to validate that the route is valid. For example, checking if a user exists before showing a page:

var routerData = PageRouterData({
  '/users/:id': RoutePath(
    validator: (params) async {
      // If this is `false`, the route isn't navigated to.
      var exists = await _checkIfUserExists(params[':id']);
      return exists;
    },
    builder: (context, params) => MaterialPage(
      child: Scaffold(
        body: Center(
          child: Text('User ID: ${params[":id"]}'),
        ),
      ),
    ),
  ),
});

If the validation failed, a call to PageRouter.of(context).pushNamed('/users/123') will return false, perhaps with a result object containing a message.

Issue: Including pages on the stack

Right now, all underlying pages are cleared when a page is navigated to (either by a linking directly via deep link or but manually updating the URL).

Instead, RoutePaths should be able to be configured to be included underneath by adding a flag

library app;

var routerData = PageRouterData.hierarchical({
  '/': RoutePath(
    // Indicate that this page should be included when any page underneath is
    // routed to.
    includeInPageStack: true, 
    builder: (context, params) {
      return MaterialPage(
        child: Scaffold(
          body: Center(
            child: Text('Details'),
          ),
        ),
      );
    },
  ),
  '/details': RoutePath(
     builder: (context, params) {
       return MaterialPage(
         child: Scaffold(
           body: Center(
             child: Text('Details'),
           ),
         ),
       );
     },
   ),
  ),
});

page_router's People

Contributors

johnpryan avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.