flutter_bloc - 为什么存储库是在 UI 而不是后端声明的?

Red*_*edZ 6 flutter flutter-bloc

我正在尝试 flutter,并且在 github 上提出了许多项目,这些项目声明了存储库并将它们传递给 UI 端的块。为什么这是正确的方法而不是在后端(在集团上)?

例子:

class MyApp extends StatelessWidget {
  final authenticationRepository = AuthenticationRepository();
  final accountRepository = AccountRepository();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      debugShowCheckedModeBanner: false,
      home: MultiRepositoryProvider(
        providers: [
          RepositoryProvider(create: (_) => authenticationRepository),
          RepositoryProvider(create: (_) => accountRepository),
        ],
        child: BlocProvider(
          create: (_) => AuthenticationBloc(
            authenticationRepository: authenticationRepository,
            accountRepository: accountRepository,
          ),
          child: Container(); // I removed the content here
          ),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

谢谢

Stu*_*uck 4

它不是关于“UI”方面,而是更多关于位于 UI 和 BLOC 之上的东西。请记住,在 Flutter 中一切都是 Widget。因此,某些小部件需要实例化和处置存储库,根据我的经验,这很可能是最顶部的小部件。

你问“为什么不在集团中创建它?”

我们不这样做,因为这会违反控制反转/依赖反转原则,并使块更难测试。我们希望从外部注入块依赖项,这样我们就可以在单元测试中控制依赖项。

另一个原因可能是存储库在多个地方使用(例如,由多个不同的块或同一块的多个实例)。存储库实例可能不应该更改,而块是根据需要在小部件树中创建的。