我正在连接到api服务器。登录后,我会收到访问权限和刷新 token 。以及用户的姓名,姓氏,权限列表等。我始终使用这些属性来显示/允许用户执行某些操作。同样,对于所有请求,我应该发送访问 token 。我正在使用BLOC模式管理登录过程,但是我不知道将所有常用数据存储在哪里。 (例如此用户数据)也许在单例类(class)中?因此,我可以在发送请求之前从该类获取数据。
您对此有何建议?因为我不知道
最佳答案
在评论中进行一些讨论之后,我还要添加答案。
BLoC类不仅用于处理逻辑,还用于存储数据。
在StatefulWidget
和StatelessWidget
内部,是的,您可以使用context
来访问bloc提供程序,但是要在bloc之间进行访问,您只需使用singleton
即可。那么如何创建单例呢?
有两种基本方法:
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
}
因此,在另一个集团内部使用集团将是这样的:
class BlocA{ //this is for second method
final blocB = BlocB();
blocB.method();...
}
对于上面的第一个方法,仅使用对象。