Flutter best architecture patterns

Do I need to write widget for all such things? Or did I get it wrong?

Let me start by saying that flutter is flexible enough to allow you to adopt any pattern you have been using before and from MVVM, MVC, Redux, Mobx, Bloc, Provider, Riverpod etc pp there are many patterns out there which you can lean on.

Q: Do all services have to be widgets?

A: It depends.

Lets talk about “getting” the services first (dependency injection)

Using Widgets is just one way of doing dependency injection in Flutter which has the huge benefit of being scoped (only available to the children of the widget) and also of being disposed when this part of the widgettree is no longer needed (a bit over simplified).

There are other DI systems like getIt which don’t rely on the widget tree – and you can do fancy stuff with getIt which is cumbersome to do in many of the others which rely on the build context to provide access to the object.

Imho in most cases you would not want to have your logic/ service in a widget but in a separate class which is then “provided” via a widget (e.g. using Provider, or by injecting it via getIt into the widget).

About “best practices”:

There are many cool patterns which all have their pros and cons.

If you have a big team or the developers are changing often you might want to use a more rigid and biased system like BLOC (using the bloc library) – if you are solo or have enough time on your hands to do your own research, there might be patterns which better suit your needs. There is no one size fits all answer to this question.

For further research I would point towards the Flutter Architecture samples and the corresponding Github repo, there might be more examples in the Pull Request section

Leave a Comment