使用提供程序体系结构进行Flutter身份验证和数据持久性

时间:2020-10-05 15:33:32

标签: flutter authentication provider state-management

我来自HTML / CSS / JQUERY作为前端背景,并且大多数时候我是Nodejs后端开发人员。 但是,我接管的一个项目是基于HTML / CSS / JQuery和PHP的,在他们需要移动应用程序之前,我一直做得很好。 所以我的选择是扑朔迷离,因为那时候很热。 我已经掌握了flutter的基础知识,并把提供程序作为我的状态管理,并且在其中集成了逻辑。 但是我有2个我无法弄清的问题。

  1. 一种是即使强制关闭应用程序,提供程序中的状态持久性。
  2. 除非已注销,否则保持登录持久性;如果已注销,则保持清除状态。

对于1.我无法找到一个具体的解决方案,除了应用程序存储,但是我不得不写很多代码来存储所有数据和类。

对于2。我做了如下实验方法

runApp(
    ChangeNotifierProvider(
      create: (_) => UserRepository(), // Here is my auth state provider
      child: MyApp(),
    ),
  );

在UserRepository类中,用户数据(如用户ID)存储在SharedPreferences中,SharedPreferences检查是否存储了userdata,因此Status根据条件变为Authenticated或Uninitialized。

下面是一个有状态的小部件,用于设置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())),
          );
        });
      }
    }

1 个答案:

答案 0 :(得分:0)

您可以使用authStateChanges()和StreamBuilder来获取身份验证状态。

Reference

相关问题