简体   繁体   English

使用 bloc 保持存储库实例“活着”

[英]keeping repository instance "alive" with bloc

I am still with my first bloc based app, adding features.我仍然使用我的第一个基于 bloc 的应用程序,添加功能。 While previously, I stored some of my page specific data with the bloc class, for the last feature, I now moved most variables into its repository.以前,我使用 bloc 类存储了一些特定于页面的数据,但对于最后一个功能,我现在将大多数变量移动到其存储库中。 I already feared that the instance of calling the repository gets lost, afterwards, which now proved true.我已经担心调用存储库的实例会丢失,之后,现在证明是正确的。

Is there a proper, easy way to make the instance persistent?有没有一种适当、简单的方法来使实例持久化?

I know of inherited widgets, however, I have not yet figured out how to implement this and my question around this unfortunately remained unanswered.我知道继承的小部件,但是,我还没有想出如何实现这一点,不幸的是,我对此的问题仍未得到解答。 It would be great, if someone could point me to some direction!如果有人能指出我的方向,那就太好了!

In general, my idea was to have the api dealing with local files and online data, the repository with frequently re-used data (session data, presented data etc) and helper variables within the bloc.一般来说,我的想法是让 api 处理本地文件和在线数据,存储经常重用的数据(会话数据、呈现的数据等)和块内的辅助变量。 So when the UI requests data, the bloc asks the repository which will either return a value stored in a variable or request a value from the api.因此,当 UI 请求数据时,块会询问存储库,该存储库将返回存储在变量中的值或从 api 请求值。

This is, how the strucuture basically looks like (hope I have not missed anything significant)这是,结构基本上是这样的(希望我没有遗漏任何重要的东西)

void main() async {
  final UserRepository userRepository = UserRepository(); // <===== userRepository initialized
  runApp(MyApp(userRepository: UserRepository()));
}

class MyApp extends StatelessWidget {
  MyApp({Key key, this.userRepository}) : assert(userRepository != null), super(key: key);
  final UserRepository userRepository;

  @override
  Widget build(BuildContext context) {
    return BlocProvider<UserBloc>(  <====== userBloc injection to top of widget tree 
      create: (_) => UserBloc(userRepository: userRepository)..add(AppStarted()),
      child: App(),
    );
  }
}
// =================================================== APP WITH ROUTES
class App extends StatelessWidget {
  App({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      routes: {
        '/': (_) => HomePage(),
        'feature 1': (_) => HomePage(),
      },
    );
  }
}
// =================================================== LANDING PAGE WITH MAIN MENU
class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage>  { 
  @override
  Widget build(BuildContext context) {
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    return CupertinoPageScaffold(
      navigationBar: CupertinoNavigationBar(
        middle: Text('MathUup'),
      ),
      child: SafeArea(
        child: CupertinoButton(
          child: Text('Feature 1',
              onPressed: () => Navigator.pushNamed(context, 'feature 1'),
  ),)));
}}     
// =================================================== BLOC
class UserBloc extends Bloc<UserEvent, UserState> {
  UserBloc({this.userRepository}) : super(AppInitial());
  final UserRepository userRepository;
  ...
    
      final user = await userRepository.getActiveUserData(userId);
      final lastSessionData = await userRepository.getLastSession(userId);
  ...
}
// =================================================== REPOSITORY
class UserRepository {
  UserRepository();
  final UserApiClient achievementsApiClient = UserApiClient();
  final SessionsApiClient sessionsApiClient = SessionsApiClient();
  UserSession activeUserSession;
  User activeUserData;
  
  
  Future<String> getLastUserId() async {
    final lastUserId = await sessionsApiClient.getLastUserId();
    return lastUserId;
  }
  Future<UserSession> getActiveUser() async {
    if (activeUserSession == null) {
      activeUserSession = await sessionsApiClient.getLastUser();
    }
    return activeUserSession;
  }
}
  
  

This line is creating and initializing your user repository:这一行正在创建和初始化您的用户存储库:

final UserRepository userRepository = UserRepository(); // <===== userRepository initialized

However, this line is not passing that repository, it's creating a new repository, ignoring the one you just initialized:但是,这一行并没有传递该存储库,而是创建了一个存储库,忽略了您刚刚初始化的存储库:

runApp(MyApp(userRepository: UserRepository()));

I think you meant to use the variable you already have:我认为您打算使用您已经拥有的变量:

runApp(MyApp(userRepository: userRepository));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM