flutter_bloc - Why are repositories declared on the UI and not the backend?

Viewed 726

Im experimenting with flutter, and ive came up with many projects on github that declare the repositories and pass them to the bloc on the UI side. Why is that the proper way to do it and not on the backend side (on the bloc) ?

Example:

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

Thank you

2 Answers

It is not about "the UI" side, but more about the thing that sits above UI and BLOCs. Remember, that in Flutter everything is a Widget. So some Widget will need to instantiate and dispose the repository and from my experience this is most likely a widget at the very top.

You ask "Why not create it in the Bloc?"

We don't do this, because that would violate inversion of control / dependency inversion principle and would make the blocs harder to test. We want to inject the blocs dependencies from outside, so we can control the dependency in a unit test.

Another reason can be that repositories are used in several places (e.g. by multiple different blocs or multiple instances of the same bloc). The repository instance probably should not change, while blocs are created on demand in the widget tree.

BLoC was created because developers were looking for a way to use the same business logic in dart applications of different platforms. For this to work, BLoCs should be implemented independently of the underlying platform.

Usually BLoCs access data using repository interfaces whose implementation can be platform-specific. Therefore, they are injected into the BLoC from the outside (e.g. from Flutter or AngularDart).

Paolo Soares came up with BLoC and he explains it here: https://www.youtube.com/watch?v=PLHln7wHgPE

Related