memory-management - 将常用数据存储在内存中

标签 memory-management flutter dart

我正在连接到一个 api 服务器。登录后,我收到访问权限和刷新 token 。还有用户名、姓氏、权限列表等。我总是使用这些属性来显示/允许用户做某事。对于所有请求,我还应该发送访问 token 。我正在使用 BLOC 模式管理登录过程,但我不知道将所有常用数据存储在何处。 (比如这个用户数据)也许在单例类中?所以我可以在发送请求之前从那个类中获取数据。

您对此有什么建议吗?因为我不知道。

最佳答案

在评论中进行了一些讨论之后,我也添加了答案。

BLoC 类不仅用于处理逻辑,还为内存保留数据。

StatefulWidgetStatelessWidget 中,是的,您可以使用 context 访问 bloc 提供程序,但是对于 bloc 之间的访问,您可以简单地使用 单例。那么如何创建单例呢?

有两种基本方法:

class Bloc{
....//some logic and variable
}

final bloc = Bloc(); //Singleton object for bloc, it's static because
// it's outside of the Class and it can be directlry accessible for
// any file that imports this file

class Bloc{
....//some logic and variable

Bloc._internal(); // private constructor

static final bloc = Bloc._internal(); // static object which will sent
// through public factory

factory Bloc() => bloc; // when you use this constructor through your
// application, you'll always get same instance

}

所以,在另一个 bloc 中使用一个 bloc 就像这样:

class BlocA{ //this is for second method

final blocB = BlocB();

blocB.method();...

}

对于上面的第一个方法,使用对象,仅此而已。

关于memory-management - 将常用数据存储在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158906/

相关文章:

c++ - 使用 malloc() 强制垃圾收集/压缩

c - 为char数组分配内存以连接已知的文本和整数

c - 销毁(免费)链表式堆栈中的所有内容?

Flutter:在启​​动时初始化变量

flutter - 如何删除然后重新安装 Flutter

flutter - 有没有办法在 dart 中实现内部类?

c++ - C++中的指针和内存分配

flutter - 获取用户的 Flutter Web 位置

sqlite - 我如何解决sqlite数据库E/SQLiteLog(16449)中的此类错误: “Order”附近的(1):语法错误

firebase - 如何使用 flutter 和 firebase 将 'Read' 功能添加到消息传递应用程序中