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

Issue

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

Solution

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.

Answered By – Stuck

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *