Flutter-存储经过身份验证的用户详细信息 [英] Flutter - Storing Authenticated User details

查看:60
本文介绍了Flutter-存储经过身份验证的用户详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Flutter的新手,我正在编写一个需要用户登录的应用程序.我已经有一个为我提供JWT的API.然后,我使用安全存储库来存储它.

I am new to Flutter and I am writing an app which requires users to login. I already have an API that provides me with a JWT. I then store this using the secure storage library.

一旦用户获得了令牌的200 OK,我想向服务器发送另一个请求以检索用户的详细信息并将其存储在单例类中,因此我可以在整个应用程序中使用它,直到他登录为止出去.现在,提供者和BLoC泛滥成灾.

Once the user gets the 200 OK with the token, I want to send another request to the server to retrieve the user's details and store it in a kind of singleton class, so I can use it through out the app until he logs out. There are so many buzzwords being thrown at me right now, Providers and BLoCs.

我想知道将当前登录的用户详细信息存储在应用程序中的最佳实践是什么?以前,我已经知道将数据存储在单例类中.但是现在我不确定该写单例类还是提供者?(我对提供方和BLoC的工作方式仍然不了解.

I was wondering what is the best practice to store the current logged in user details in the app? Previously I've been aware of storing the data in a singleton class. But now I'm not sure whether I should write a singleton class or a Provider? (I'm still rusty on my knowledge about how Providers and BLoCs work).

推荐答案

从简单开始

一个简单的存储数据的起点(我假设它是键/值对的形式)将使用共享首选项.

A simple starting point to store the data, which i assume is the form of key/value pairs, would be using shared preferences.

什么是共享首选项

共享首选项"的主要用途是保存用户首选项,设置,甚至是数据(如果不是太大的话),以便下次启动应用程序时,可以检索和使用这些信息.

The main use of Shared Preferences is to save user preferences, settings, maybe data (if not too large) so that next time the application is launched, these pieces of information could be retrieved and used.

使用方法

设置共享首选项"的实例变量,并使用键标识符存储该值.每当您想在应用程序启动时检索值时,只需使用键即可获取它.请参阅下面的示例来设置和获取存储的用户名.

Set an instance variable of Shared Preferences and store the value with a key identifier. Any time you want to retrieve the value when the app starts, just get it using the key. See example below of setting and getting a stored username.

Future<bool> setUserName(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.setString("username",value);
}

Future<String> getUserName(String value) async {
final SharedPreferences prefs = await SharedPreferences.getInstance();
    return prefs.getString("username");
}

安装要安装共享的首选项,请将其添加到程序包的pubspec.yaml文件中:

Installation To installed shared preferences, add this to your package's pubspec.yaml file:

dependencies:
  shared_preferences: ^0.5.7+3

打包页面上的更多信息.

这篇关于Flutter-存储经过身份验证的用户详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆