gpt4 book ai didi

flutter - 在 Flutter 中创建私有(private)路由

转载 作者:行者123 更新时间:2023-12-03 02:47:26 26 4
gpt4 key购买 nike

如何在我的私有(private)路由上创建一个包装器,仅当用户被授权时才导航到屏幕,否则重定向到登录并在登录后返回原始屏幕。
如何以一种通用的方式实现这一点,以便我在其他私有(private) future 屏幕上重复使用它?

最佳答案

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

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 - 在 Flutter 中创建私有(private)路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63129318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com