DEV Community

Ken Ng
Ken Ng

Posted on • Edited on

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

Top comments (0)