【发布时间】:2021-01-20 12:05:48
【问题描述】:
我来自前端背景的 HTML/CSS/JQUERY,而且我主要是一名 Nodejs 后端开发人员。 然而,我接手的一个项目是基于 HTML/CSS/JQuery 和 PHP 的,我在这方面做得很好,直到他们需要一个移动应用程序。 所以我的选择是颤抖的,因为那一刻很热。 我已经掌握了 Flutter 的基础知识,并将 provider 作为我的状态管理,并在其中加入了逻辑。 但是我有 2 个问题我无法弄清楚。
- 一个是提供程序中的状态持久性,即使应用程序被强制关闭。
- 保持登录持久性,除非注销,如果注销则清除状态。
对于 1. 除了应用程序存储之外,我还没有找到具体的解决方案,但是我必须编写更多代码来将所有数据和类存储到其中。
对于2.我做了一些实验方法如下
runApp(
ChangeNotifierProvider(
create: (_) => UserRepository(), // Here is my auth state provider
child: MyApp(),
),
);
在 UserRepository 类中,用户 ID 等用户数据存储在 SharedPreferences 中,SharedPreferences 检查是否存储了用户数据,因此根据条件状态变为已验证或未初始化。
下面是一个有状态的小部件,用于设置与 UserRepository 相关的状态
class _MyAppState extends State<MyApp> {
ProjectRepository projectRepository = ProjectRepository();
UIKeypadRepository uiKeypadRepository = UIKeypadRepository();
PODRepository podRepository = PODRepository();
Status currentStatus;
//Also there are more Change notifier class here that manages state of various features of the app
void initProviders() {
projectRepository = ProjectRepository();
uiKeypadRepository = UIKeypadRepository();
podRepository = PODRepository();
}
@override
void initState() {
currentStatus = Provider.of<UserRepository>(context, listen: false).status;
//if not logged out current status is authenticated
super.initState();
}
@override
Widget build(BuildContext context) {
return Consumer(builder: (context, UserRepository authStatus, child) {
if (currentStatus != Status.Authenticated) {
initProviders(); // this function is called and all changenotifier classes are reinitialized
}
return MultiProvider(
providers: [
ChangeNotifierProvider.value(value: projectRepository),
ChangeNotifierProvider.value(value: uiKeypadRepository),
ChangeNotifierProvider.value(value: podRepository),
],
//instead of create I used value so if classes are initialized initial values are taken else existing values are made available to below the widget tree
child: MaterialApp(
home: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
FocusScope.of(context).requestFocus(FocusNode());
},
child: LandingPage())),
);
});
}
}
【问题讨论】:
标签: flutter authentication provider state-management