Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

beamer

handle your application routing, synchronize it with browser url and more. beamer uses the power of router and implements all the underlying logic for you.

quick start

for a simple application, simplelocationbuilder is an appropriate choice which yields the least amount of code for a functioning application:

class myapp extends statelesswidget {
  @override
  widget build(buildcontext context) {
    return materialapp.router(
      routeinformationparser: beamerrouteinformationparser(),
      routerdelegate: beamerrouterdelegate(
        locationbuilder: simplelocationbuilder(
          routes: {
            '/': (context) => homescreen(),
            '/books': (context) => booksscreen(),
            '/books/:bookid': (context) => bookdetailsscreen()
          },
        ),
      ),
    );
  }
}

navigating through those routes can be done with

beamer.of(context).beamtonamed('/books/2');

// or
context.beamtonamed('/books/2');

and accessing route attributes (for example, bookid for building bookdetailsscreen) can be done with

beamer.of(context).currentlocation.state.pathparameters['bookid'];

// or
context.currentbeamlocation.state.pathparameters['bookid'];

key concepts

for a fairly large app, it is recommended to use beamer in its “natural” form.

beamlocation

the most important construct in beamer is a beamlocation which represents a stack of one or more pages.
beamlocation has 3 important roles:

  • know which uris it can handle: pathblueprints
  • know how to build a stack of pages: pagesbuilder
  • keep a state that provides a link between the first 2

beamlocation is an abstract class which needs to be extended. the purpose of having multiple beamlocations is to architecturally separate unrelated “places” in an application.

for example, bookslocation can handle all the pages related to books and articleslocation everything related to articles. in the light of this scoping, beamlocation also has a builder for wrapping an entire stack of its pages with some provider so the similar data can be shared between similar pages.

this is an example of beamlocation:

class bookslocation extends beamlocation {
  bookslocation(beamstate state) : super(state);

  @override
  list<string> get pathblueprints => ['/books/:bookid'];

  @override
  list<beampage> pagesbuilder(buildcontext context, beamstate state) => [
        beampage(
          key: valuekey('home'),
          child: homescreen(),
        ),
        if (state.uri.pathsegments.contains('books'))
          beampage(
            key: valuekey('books'),
            child: booksscreen(),
          ),
        if (state.pathparameters.containskey('bookid'))
          beampage(
            key: valuekey('book-${state.pathparameters['bookid']}'),
            child: bookdetailsscreen(
              bookid: state.pathparameters['bookid'],
            ),
          ),
      ];
}

beamstate

this is the above-mentioned state of beamlocation. its role is to keep various uri attributes such as pathblueprintsegments (the segments of chosen pathblueprint, as each beamlocation supports many of those), pathparameters, queryparameters and arbitrary key-value data. those attributes are important while building pages and for beamstate to create an uri that will be consumed by the browser.

besides purely imperative navigation via e.g. beamtonamed('/books/3'), this also provides a method to have declarative navigation by changing the state of beamlocation. for example:

beamer.of(context).currentlocation.update(
  (state) => state.copywith(
    pathblueprintsegments: ['books', ':bookid'],
    pathparameters: {'bookid': '3'},
  ),
),

beamstate can be extended with a completely custom state which can be used for beamlocation, for example:

class bookslocation extends beamlocation<mystate> {...}

it is important in this case that customstate has an uri getter which is needed for browser’s url bar.

beaming

navigating between or within beamlocations is achieved by beaming. you can think of it as teleporting (beaming) to another place in your app. similar to navigator.of(context).pushreplacementnamed('/my-route'), but beamer is not limited to a single page, nor to a push per se. beamlocations hold an arbitrary stack of pages that get built when you beam there. using beamer can feel like using many of navigator‘s push/pop methods at once.

examples of beaming:

beamer.of(context).beamto(mylocation());

// or with an extension on buildcontext
context.beamto(mylocation());
context.beamtonamed('/books/2');

// or more explicitly
context.beamto(
  bookslocation(
    beamstate(
      pathblueprintsegments: ['books', ':bookid'],
      pathparameters: {'bookid': '2'},
    ),
  ),
),
context.beamtonamed(
  '/book/2',
  data: {'note': 'this is my favorite book'},
);

updating

once at a beamlocation, it is preferable to update the current location’s state. for example, for going from /books to /books/3 (which are both handled by bookslocation):

context.currentbeamlocation.update(
  (state) => state.copywith(
    pathblueprintsegments: ['books', ':bookid'],
    pathparameters: {'bookid': '3'},
  ),
),

note that both beaming functions (beamto and beamtonamed) will have the same effect as update when you try to beam to a location which you’re currently on, e.g. if you called context.beamtonamed('/books/3') instead of above code.

beaming back

all beamlocations that you visited are kept in beamhistory. therefore, there is an ability to beam back to the previous beamlocation. for example, after spending some time on /books and /books/3, say you beam to /articles which is handled by another beamlocation (e.g. articleslocation). from there, you can get back to your previous location as it were when you left, i.e. /books/3.

context.beamback();

note that beamer will remove duplicate locations from beamhistory as you go. for example, if you visit bookslocation, articleslocation and then bookslocation again, the first instance of bookslocation will be removed from history and beamhistory will be [articleslocation,bookslocation] instead of [bookslocation,articleslocation,bookslocation]. you can turn that off by setting beamerrouterdelegate.removeduplicatehistory to false.

note that beamer can integrate android’s back button to do beamback if possible when all the pages from current beamlocation have been popped. this is achieved by setting a back button dispatcher in in materialapp.router.

backbuttondispatcher: beamerbackbuttondispatcher(delegate: routerdelegate)

you can check whether you can beam back with context.canbeamback or even inspect the location you’ll be beaming back to: context.beambacklocation.

usage

lastly, we go through a couple of notes on how and where to put beamer.

on entire app

to use beamer on your entire app, you must (as per official documentation) construct your *app widget with .router constructor to which (along with all your regular *app attributes) you provide

  • routeinformationparser that parses an incoming uri.
  • routerdelegate that controls (re)building of navigator

here you use the beamer implementation of those – beamerrouteinformationparser and beamerrouterdelegate, to which you pass your locationbuilder.

in the simplest form, locationbuilder is just a function which takes the current beamstate and returns a custom beamlocation based on the uri or other state properties.

class myapp extends statelesswidget {
  final routerdelegate = beamerrouterdelegate(
    locationbuilder: (state) {
      if (state.uri.pathsegments.contains('books')) {
        return bookslocation(state);
      }
      return homelocation(state);
    },
  );
  @override
  widget build(buildcontext context) {
    return materialapp.router(
      routerdelegate: routerdelegate,
      routeinformationparser: beamerrouteinformationparser(),
      backbuttondispatcher:
          beamerbackbuttondispatcher(delegate: routerdelegate),
    );
  }
}

there are also two other options available, if you don’t want to define a custom locationbuilder function.

with a list of beamlocations

you can use the beamerlocationbuilder with a list of beamlocations. this builder will automatically select the correct location, based on the pathblueprints of each beamlocation. in this case, define your beamerrouterdelegate like this:

final routerdelegate = beamerrouterdelegate(
  locationbuilder: beamerlocationbuilder(
    beamlocations: [
      homelocation(),
      bookslocation(),
    ],
  ),
);

with a map of routes

you can use the simplelocationbuilder with a map of routes and widgetbuilders, as mentioned in quick start. this completely removes the need for custom beamlocations, but also gives you the least amount of customizability. still, wildcards and path parameters in your paths are supported as with all the other options.

final routerdelegate = beamerrouterdelegate(
  locationbuilder: simplelocationbuilder(
    routes: {
      '/': (context) => homescreen(),
      '/books': (context) => booksscreen(),
      '/books/:bookid': (context) => bookdetailsscreen(
        bookid: context.currentbeamlocation.state.pathparameters['bookid'],
      ),
    },
  ),
);

deeper in the tree

if there is a need for nested navigation, beamer will be put somewhere deeper in the tree. in this case, it is a must to set rootrouterdelegate instead of beamerrouterdelegate as the top-most router delegate. then, we have 2 options:

  • provide homebuilder to rootrouterdelegate which will serve the same role as materialapp.home. this is useful when you need a simple app with some navigation bar.
class myapp extends statelesswidget {
  @override
  widget build(buildcontext context) {
    return materialapp.router(
      routeinformationparser: beamerrouteinformationparser(),
      routerdelegate: rootrouterdelegate(
        homebuilder: (context, uri) => scaffold(
          body: beamer(
            locationbuilder: _locationbuilder,
          ),
          ...
        ),
      ),
      ...
    );
  }
}
  • provide locationbuilder to rootrouterdelegate as we would to beamerrouterdelegate and have beamer somewhere deep within those locations (see nested navigation example).
class myapp extends statelesswidget {
  @override
  widget build(buildcontext context) {
    return materialapp.router(
      routeinformationparser: beamerrouteinformationparser(),
      routerdelegate: rootrouterdelegate(
        locationbuilder: beamerlocationbuilder(
          beamlocations: [
            homelocation(),
            bookslocation(),
            articleslocation(),
          ],
        ),
      ),
      ...
    );
  }
}

general notes

  • when extending beamlocation, two methods need to be implemented: pathblueprints and pagesbuilder.
    • pagesbuilder returns a stack of pages that will be built by navigator when you beam there, and pathblueprints is there for beamer to decide which beamlocation corresponds to which uri.
    • beamlocation keeps query and path parameters from uri in its beamstate. the : is necessary in pathblueprints if you might get path parameter from browser.
  • beampage‘s child is an arbitrary widget that represents your app screen / page.
    • key is important for navigator to optimize rebuilds. this should be a unique value for “page state”.
    • beampage creates materialpageroute by default, but other transitions can be chosen by setting beampage.type to one of available beampagetype.

note that “navigator 1.0” can be used alongside beamer. you can easily push or pop pages with navigator.of(context), but those will not be contributing to the uri. this is often needed when some info/helper page needs to be shown that doesn’t influence the browser’s url. and of course, when using beamer on mobile, this is a non-issue as there is no url.

examples

books

here is a recreation of books example from this article where you can learn a lot about navigator 2.0. see example for full application code of this example.

example-books

advanced books

for a step further, we add more flows to demonstrate the power of beamer. the full code is available here.

example-advanced-books

deep location

you can instantly beam to a location in your app that has many pages stacked (deep linking) and then pop them one by one or simply beamback to where you came from. the full code is available here. note that beambackonpop parameter of beamto might be useful here to override appbar‘s pop with beamback.

example-deep-location

elevatedbutton(
  onpressed: () => context.beamto(deeplocation('/a/b/c/d')),
  // onpressed: () => context.beamto(deeplocation('/a/b/c/d'), beambackonpop: true),
  child: text('beam deep'),
),

location builder

you can override beamlocation.builder to provide some data to the entire location, i.e. to all the pages. the full code is available here.

example-location-builder

// in your location implementation
@override
widget builder(buildcontext context, navigator navigator) {
  return myprovider<myobject>(
    create: (context) => myobject(),
    child: navigator,
  );
}

guards

you can define global guards (for example, authentication guard) or location guards that keep a specific location safe. the full code is available here.

example-guards

  • global guards
beamerrouterdelegate(
  guards: [
    beamguard(
      pathblueprints: ['/books*'],
      check: (context, location) => authenticationstateprovider.of(context).isauthenticated.value,
      beamto: (context) => loginlocation(),
    ),
  ],
  ...
),
  • location (local) guards
// in your location implementation
@override
list<beamguard> get guards => [
  beamguard(
    pathblueprints: ['/books/*'],
    check: (context, location) => location.pathparameters['bookid'] != '2',
    showpage: forbiddenpage,
  ),
];

beamer widget

examples of putting beamers into the widget tree, when you need nested navigation.

example-bottom-navigation-mobile

example-bottom-navigation-multiple-beamers

example-nested-navigation

class myapp extends statelesswidget {
  final _beamerkey = globalkey<beamerstate>();

  @override
  widget build(buildcontext context) {
    return materialapp.router(
      routeinformationparser: beamerrouteinformationparser(),
      routerdelegate: rootrouterdelegate(
        homebuilder: (context, uri) => scaffold(
          body: beamer(
            key: _beamerkey,
            routerdelegate: beamerrouterdelegate(
              locationbuilder: (state) {
                if (state.uri.pathsegments.contains('books')) {
                  return bookslocation(state);
                }
                return articleslocation(state);
              },
            ),
          ),
          bottomnavigationbar: bottomnavigationbarwidget(
            beamerkey: _beamerkey,
          ),
        ),
      ),
    );
  }
}
class myappstate extends state<myapp> {
  int _currentindex = 0;

  @override
  widget build(buildcontext context) {
    return materialapp(
      home: scaffold(
        body: indexedstack(
          index: _currentindex,
          children: [
            beamer(
              routerdelegate: beamerrouterdelegate(
                locationbuilder: (state) => articleslocation(state),
              ),
            ),
            container(
              color: colors.blueaccent,
              padding: const edgeinsets.all(32.0),
              child: beamer(
                routerdelegate: beamerrouterdelegate(
                  locationbuilder: (state) => bookslocation(state),
                ),
              ),
            ),
          ],
        ),
        bottomnavigationbar: bottomnavigationbar(
          currentindex: _currentindex,
          items: [
            bottomnavigationbaritem(label: 'a', icon: icon(icons.article)),
            bottomnavigationbaritem(label: 'b', icon: icon(icons.book)),
          ],
          ontap: (index) => setstate(() => _currentindex = index),
        ),
      ),
    );
  }
}
...

class myapp extends statelesswidget {
  @override
  widget build(buildcontext context) {
    return materialapp.router(
      routeinformationparser: beamerrouteinformationparser(),
      routerdelegate: rootrouterdelegate(
        locationbuilder: (state) => homelocation(state),
      ),
    );
  }
}

...


class homelocation extends beamlocation {
  @override
  list<string> get pathblueprints => ['/*'];

  @override
  list<beampage> pagesbuilder(buildcontext context) => [
        beampage(
          key: valuekey('home'),
          child: homescreen(),
        )
      ];
}

...

class homescreen extends statelesswidget {
  final _beamerkey = globalkey<beamerstate>();

  @override
  widget build(buildcontext context) {
    return scaffold(
      appbar: appbar(
        title: text('home'),
      ),
      body: row(
        children: [
          container(
            color: colors.blue[300],
            padding: const edgeinsets.all(16.0),
            child: column(
              children: [
                elevatedbutton(
                  onpressed: () => _beamerkey.currentstate.routerdelegate
                      .beamtonamed('/books'),
                  child: text('books'),
                ),
                sizedbox(height: 16.0),
                elevatedbutton(
                  onpressed: () => _beamerkey.currentstate.routerdelegate
                      .beamtonamed('/articles'),
                  child: text('articles'),
                ),
              ],
            ),
          ),
          container(width: 1, color: colors.blue),
          expanded(
            child: beamer(
              key: _beamerkey,
              routerdelegate: beamerrouterdelegate(
                locationbuilder: (state) {
                  if (state.uri.pathsegments.contains('books')) {
                    return bookslocation(state);
                  }
                  if (state.uri.pathsegments.contains('articles')) {
                    return articleslocation(state);
                  }
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

example-animated-rail


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD


Download this source code for
5 USD

Comments are closed.