flutter_bloc - 为什么要在 UI 而不是后端声明存储库?
flutter_bloc - Why are repositories declared on the UI and not the backend?
我正在试验 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
),
),
),
);
}
}
谢谢
这不是关于“UI”方面,而是关于位于 UI 和 BLOC 之上的东西。请记住,在 Flutter 中,一切都是 Widget。所以一些 Widget 将需要实例化和处理存储库,根据我的经验,这很可能是最顶部的 widget。
你问“为什么不在 Bloc 中创建它?”
我们不这样做,因为那样会违反控制反转/依赖反转原则,并且会使区块更难测试。我们想从外部注入 blocs 依赖,所以我们可以在单元测试中控制依赖。
另一个原因可能是存储库在多个地方使用(例如,多个不同的集团或同一集团的多个实例)。存储库实例可能不应该更改,而块是在小部件树中按需创建的。
BLoC 的创建是因为开发人员正在寻找一种在不同平台的 dart 应用程序中使用相同业务逻辑的方法。为此,BLoC 应独立于底层平台实施。
通常 BLoC 使用存储库接口访问数据,其实现可以是特定于平台的。因此,它们是从外部(例如从 Flutter 或 AngularDart)注入到 BLoC 中的。
Paolo Soares 提出了 BLoC,他在这里进行了解释:https://www.youtube.com/watch?v=PLHln7wHgPE
我正在试验 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
),
),
),
);
}
}
谢谢
这不是关于“UI”方面,而是关于位于 UI 和 BLOC 之上的东西。请记住,在 Flutter 中,一切都是 Widget。所以一些 Widget 将需要实例化和处理存储库,根据我的经验,这很可能是最顶部的 widget。
你问“为什么不在 Bloc 中创建它?”
我们不这样做,因为那样会违反控制反转/依赖反转原则,并且会使区块更难测试。我们想从外部注入 blocs 依赖,所以我们可以在单元测试中控制依赖。
另一个原因可能是存储库在多个地方使用(例如,多个不同的集团或同一集团的多个实例)。存储库实例可能不应该更改,而块是在小部件树中按需创建的。
BLoC 的创建是因为开发人员正在寻找一种在不同平台的 dart 应用程序中使用相同业务逻辑的方法。为此,BLoC 应独立于底层平台实施。
通常 BLoC 使用存储库接口访问数据,其实现可以是特定于平台的。因此,它们是从外部(例如从 Flutter 或 AngularDart)注入到 BLoC 中的。
Paolo Soares 提出了 BLoC,他在这里进行了解释:https://www.youtube.com/watch?v=PLHln7wHgPE