我正在连接到一个 api 服务器。登录后,我收到访问权限和刷新 token 。还有用户名、姓氏、权限列表等。我总是使用这些属性来显示/允许用户做某事。对于所有请求,我还应该发送访问 token 。我正在使用 BLOC 模式管理登录过程,但我不知道将所有常用数据存储在何处。 (比如这个用户数据)也许在单例类中?所以我可以在发送请求之前从那个类中获取数据。
您对此有什么建议吗?因为我不知道。
最佳答案
在评论中进行了一些讨论之后,我也添加了答案。
BLoC 类不仅用于处理逻辑,还为内存保留数据。
在 StatefulWidget
和 StatelessWidget
中,是的,您可以使用 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/