Making Private Route in Flutter


How can I make a wrapper over my private routes, which navigate to screen only when user is authorized, otherwise redirect to login and get back to the original screen after login.
How can make this in a generalized way, so that I just reuse it on my other Private future screens?


If you are using routes parameter in your MaterialApp, you can replace it with following implementation

import 'dart:collection';

import 'package:flutter/widgets.dart';

class ConditionalRouter extends MapMixin<String, WidgetBuilder> {
  final Map<String, WidgetBuilder> public;
  final Map<String, WidgetBuilder> private;

  ConditionalRouter({this.public, this.private});

  WidgetBuilder operator [](Object key) {
    if (public.containsKey(key))
      return public[key];
    if (private.containsKey(key)) {
      if (MyAuth.isUserLoggedIn)
        return private[key];
      // Adding next page parameter to your Login page
      // will allow you to go back to page, that user were going to
      return (context) => LoginPage(nextPage: key);
    return null;

  void operator []=(key, value) {}

  void clear() {}

  Iterable<String> get keys {
    final set = Set<String>();
    return set;

  WidgetBuilder remove(Object key) {
    return public[key] ?? private[key];

And use it like that:

  // ...
  routes: ConditionalRouter(
    public: {
      '/start_page': (context) => StartPage()
    private: {
      '/user_profile': (context) => UserProfilePage()

Answered By – Dima Rostopira

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *