本文介绍了在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?

推荐答案

如果在MaterialApp中使用routes参数,则可以将其替换为以下实现

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});

  @override
  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;
  }

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

  @override
  void clear() {}

  @override
  Iterable<String> get keys {
    final set = Set<String>();
    set.addAll(public.keys);
    set.addAll(private.keys);
    return set;
  }

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

并像这样使用它:

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

这篇关于在Flutter中建立私人路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 17:35