DEV Community

Ken Ng
Ken Ng

Posted on • Edited on

4 3

Dart Good Practice: separate Model, UI view and controller logic

MVC architecture is a design pattern to separate the application into three parts, namely: the model part, the view and the controller.

In day to day code review, it is noticed that developers tend to directly use unprocessed model data into the UI view. Not only that this will create a lot of extra if-else null checking logic in the final compiled code, it make the code looks very verbose.

See the example with pseudocode below:

Not Recommended:

   Text(_ctrl.sales?.amount ?? ''),
   Text(_ctrl.sales?.quantity ?? ''),
   Text(_ctrl.sales?.month ?? ''),
Enter fullscreen mode Exit fullscreen mode

Good
controller.dart

late SaleModel sales;

onFetch() async {
  var res = await fetch('https://abc.com/sales');
  if (null != res.data && null != res.data.sales) {
    sales = SaleModel.fromJson(res.data.sales);
  } else {
    // declare a named constructor which return SaleModel with blank string
    sales = SaleModel.blank();
  }
}
Enter fullscreen mode Exit fullscreen mode

UI view

   Text(_ctrl.sales.amount),
   Text(_ctrl.sales.quantity),
   Text(_ctrl.sales.month),
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay