DEV Community

Cover image for What are some rules to follow for good app architecture in Flutter App?
Boris Gautier
Boris Gautier

Posted on

What are some rules to follow for good app architecture in Flutter App?

RULE: Avoid singletons

If you want your code to be testable, there are various alternatives to singletons:

  • constructor arguments (doesn't scale well with deep widget hierarchies)
  • InheritedWidget or Provider
  • Service locators

RULE: Zero (or very little) business logic in the widgets.

Widgets should be as dumb as possible and only be used to map the state to the UI.

Small exceptions: sometimes I include some simple currency, date, or number formatting code in my widgets if it makes life easier.

RULE: No Flutter code (including BuildContext) in the business logic.

Your view models/blocs/controllers are used to update the widget state in response to events.

By ensuring that these classes don't have any UI code in them, they can be easily unit tested.

RULE: Navigation code belongs to the widgets

If you try to put your navigation code in the business logic, you'll have a hard time because you need a BuildContext to do so.

Solution:

  • emit a new widget state
  • listen to the state in the widget and perform the navigation there

RULE: Show dialogs and snackbars in the widgets

Same as above. When we need to show an alert dialog because something went wrong, this is what we should do:

  • emit a new error state
  • listen to the state in the widget and use the context to show the alert dialog

RULE: Do UI validation in the widgets*

*This may be a controversial one.

FormState and TextEditingController depend on the widget lifecycle, so they shouldn't go in the view models/blocs etc.

Keep them in your widgets and offload everything else to the business logic.

Top comments (0)