【问题标题】:flutter_bloc - Why are repositories declared on the UI and not the backend?flutter_bloc - 为什么在 UI 而不是后端声明存储库?
【发布时间】:2021-09-09 04:55:17
【问题描述】:

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

例子:

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
          ),
        ),
      ),
    );
  }
}

谢谢

【问题讨论】:

  • 你能举几个例子吗?
  • @RobertSandberg 完成

标签: flutter flutter-bloc


【解决方案1】:

创建 BLoC 是因为开发人员正在寻找一种在不同平台的 dart 应用程序中使用相同业务逻辑的方法。为此,BLoC 应该独立于底层平台来实现。

通常 BLoC 使用存储库接口访问数据,其实现可以是特定于平台的。因此,它们是从外部(例如从 Flutter 或 AngularDart)注入到 BLoC 中的。

Paolo Soares 提出了 BLoC,他在此进行了解释:https://www.youtube.com/watch?v=PLHln7wHgPE

【讨论】:

    【解决方案2】:

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

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

    我们不这样做,因为这会违反控制倒置/依赖倒置原则,并且会使块更难测试。我们想从外部注入 blocs 依赖,所以我们可以在单元测试中控制依赖。

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

    【讨论】:

      猜你喜欢
      • 2010-12-20
      • 2021-12-20
      • 1970-01-01
      • 2019-08-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      相关资源
      最近更新 更多