This repository show you how apply MVP to Flutter project

Overview

Flutter MVP demo

Apply MVP to Flutter project.

To easy understand this project, you can visit my other project first which talk about ListView on Flutter at here: https://github.com/yendangn/Flutter-Simple-ListView

UI Overview

My project is using API from https://randomuser.me/ . The UI will show list of use as below. And I also apply MVP to it.

  1. Android

  1. iOS

Project structure

  1. Overview

a . common

Where will contain common UI, font, color ,custom exception.

fetch_data_exception.dart

This class will extend Exception, to handle error when get data from API.

class FetchDataException implements Exception{

  String _message;
  FetchDataException(this._message);

  String toString() {
    return "Exception: $_message";
  }
}
app_app_bar.dart

To custom AppBar component, we will use a lot app bar for project. So if we create a custom and re-use it, we will save a lot line of code.

class AppAppBar extends AppBar {

  String _title;

  AppAppBar(this._title);

  @override
  Color get backgroundColor => Colors.white;

  @override
  bool get centerTitle => true;


  @override
  double get elevation => 2.0;

  @override
  Widget get title => new Text(
        _title.toUpperCase(),
        style: new TextStyle(fontSize: 20.0, color: Colors.black, fontFamily: "Arquitecta"),
      );
}

And when you want to use it, just do as below:

@override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppAppBar("Users"),
    );
  }

Don't need modify appbar's attributes to custom

app_color.dart

This class will help us on convert hex color to Color object on Flutter.

class AppColor{

  static Color whiteColor = const Color(0x000000);
  static Color blackColor = const Color(0xFFFFFF);

}

b. feature

App's functionality , the name will mapping with functionality. Each feature forder will have:

  • Repository : will working with API or database
  • Presenter : will handle app logic, get data from repository and update view.
  • View : it is responsible for presenting data in a way decided by the presenter.
user_list_repository.dart

First, we will have a abstract class which will define method for Repository.

abstract class UserListRepository {
  Future<List<User>> fetchUser();
}

Then, we will implement above repository by create a class, like that:

class UserListRepositoryIml implements UserListRepository {

  final String _api = 'http://api.randomuser.me/?results=50';

  @override
  Future<List<User>> fetchUser() {

    return http
        .get(_api)
        .then((http.Response response) {

      final String jsonBody = response.body;
      final int statusCode = response.statusCode;

      if(statusCode != 200 || jsonBody == null){
        print(response.reasonPhrase);
        throw new FetchDataException("StatusCode:$statusCode, Error:${response.reasonPhrase}");
      }

      final JsonDecoder _decoder = new JsonDecoder();
      final useListContainer = _decoder.convert(jsonBody);
      final List userList = useListContainer['results'];

      return userList.map((contactRaw) => new User.fromJson(contactRaw) )
          .toList();

    });
  }
}

I'm using http https://pub.dartlang.org/packages/http#-installing-tab- to connect and get data from API. You can learn more at flutter document: https://flutter.io/cookbook/networking/fetch-data/

You can use JsonDecoder to parse Object from Json https://flutter.io/json/

user_list_presenter.dart

Define a abstract class , view will implement this.

abstract class UserListViewContract {
  void onLoadUserComplete(List<User> users);

  void onLoadUserError();
}

Create repository class

class UserListPresenter {
  UserListViewContract _view;
  UserListRepository _repository;

  UserListPresenter(this._view) {
    _repository = new Injector().getUserListRepository();
  }

  void loadUser() {

    assert(_view != null && _repository != null);

    _repository
        .fetchUser()
        .then((contacts) => _view.onLoadUserComplete(contacts))
        .catchError((onError) => _view.onLoadUserError());
  }
}

You can see, my repository will have UserListViewContract _view; and UserListRepository _repository; I will init _repository on contructor by Injector ( see c. id)

 UserListPresenter(this._view) {
   _repository = new Injector().getUserListRepository();
 }
 

And use _repository to get data and update view, like that:

  void loadUsers() {
   assert(_view != null && _repository != null);
   _repository
       .fetchUser()
       .then((contacts) => _view.onLoadUserComplete(contacts))
       .catchError((onError) => _view.onLoadUserError());
 }
}

View class user_list_screen.dart ( like Activity/Fragment on Android or UIViewController on iOS).

Will implement view on above step like that

class UserListState extends State<UserListScreen>
   implements UserListViewContract{
   
     //Your code
   }
   

Define and init presenter

UserListPresenter _userListPresenter;

 @override
 void initState() {
   _userListPresenter = new UserListPresenter(this);
 }

And use this presenter to get API:

  _userListPresenter.loadUser();
  

Finally, handle data:

@override
 void onLoadUserComplete(List<User> users) {
  
 }

 @override
 void onLoadUserError() {
  
 }

c. di

Dependency injection (just very simple level)

dependency_injection.dart

Injector class will provide the repository to presenter.

class Injector {
  static final Injector _singleton = new Injector._internal();

  factory Injector() {
    return _singleton;
  }

  Injector._internal();

  UserListRepository getUserListRepository() => new UserListRepositoryIml();
}

d. schema

Define data class

class User {
  Name name;
  Picture picture;
  String email;
  String phone;

  User({this.name, this.picture, this.email, this.phone});

  User.fromJson(Map<String, dynamic> json)
      : name = new Name.fromJson(json['name']),
        picture = new Picture.fromJson(json['picture']),
        email = json['email'],
        phone = json['phone'];
}

class Name {
  String last;
  String first;

  Name({this.last, this.first});

  Name.fromJson(Map<String, dynamic> json)
      : last = json['last'],
        first = json['first'];
}

class Picture {
  String medium;

  Picture({this.medium});

  Picture.fromJson(Map<String, dynamic> json) : medium = json['medium'];
}

e. main.dart

Root of project.

You might also like...

This is the Zuri Chat Android app project repository handled by TEAM SOCRATES, written with pure Flutter.

Zuri Chat Overview This is the Zuri Chat Android app project repository handled by TEAM SOCRATES, written with pure Flutter. NB: Always contact Team l

Nov 22, 2022

Production-grade project developed during the Reso Coder Academy Flutter Bootcamp: It's a mobile Github repository viewer

RepoStar - GitHub Starred Repository Manager Production-grade project developed during the Reso Coder Academy Flutter Bootcamp. It's a mobile Github s

Aug 18, 2022

Flutter project template with BloC and repository pattern.

Flutter project template with BloC and repository pattern.

Dec 10, 2022

Use the template to create your own repository, complete the project and verify

Use the template to create your own repository, complete the project and verify

Proyecto Nivelación MisionTic Usar el template para crear un repositorio propio,

Dec 20, 2021

🌈 Repository for a compass project, basically an App for displaying bank transfers, with API requests, Flag persistence, Infinite Scroll, Error Handling, Unit Tests, Extract Sharing working with SOLID, BLoC and Designer Patterns.

🌈 Repository for a compass project, basically an App for displaying bank transfers, with API requests, Flag persistence, Infinite Scroll, Error Handling, Unit Tests, Extract Sharing working with SOLID, BLoC and Designer Patterns.

💸 Green Bank Aplicação desenvolvida em Flutter com intuito de trabalhar conexão com API, Gerenciamento de estado usando BLoC, Refatoração, Arquitetur

Oct 7, 2022

This is a flutter app which uses the Bitrise Api(https://api-docs.bitrise.io/) to show the bitrise projects and builds and lets you download your artifacts.

This is a flutter app which uses the Bitrise Api(https://api-docs.bitrise.io/) to show the bitrise projects and builds and lets you download your artifacts.

Bitrise Artifact Downloader Introduction 🙋‍♂️ This is a flutter app which uses the Bitrise Api(https://api-docs.bitrise.io/) to show the bitrise proj

Apr 30, 2021

A TypeAhead (autocomplete) widget for Flutter, where you can show suggestions to users as they type

Starlight Type Ahead FLUTTER | ANDROID, IOS, LINUX, MACOS, WEB, WINDOWS A TypeAhead (autocomplete) widget for Flutter, where you can show suggestions

Dec 15, 2021

Flutter package for Android and iOS allow you to show a wide range of hyperlinks either in the input field or in an article view

Flutter package for Android and iOS allow you to show a wide range of hyperlinks either in the input field or in an article view

Tagtly package help you to detect a lot of hyperlink text such as.. email, url, social media tags, hashtag and more either when user type in text field or when appear a text read only.

Jul 25, 2022

Choose color theme template - A template will help you choose a color scheme for the application, show how widgets interact with it

Choose color theme template - A template will help you choose a color scheme for the application, show how widgets interact with it

choose_color_theme_template This template will help you choose a color scheme fo

Oct 24, 2022
Owner
Yen Dang
Yen Dang
Codeflow 19 Sep 29, 2022
This repository show you how implement a ListView on Flutter

Flutter Simple ListView UI Overview Android Category list Category detail iOS Category list Category detail Flutter component ListView https://docs.fl

Yen Dang 3 Nov 11, 2021
An MVP framework for flutter applications

mvp_core An MVP (model/view/presenter) framework for applications written in dart. This package gives specific support to the flutter framework. Getti

Josiah Saunders 3 Jan 4, 2021
O Invest App é um aplicativo de plataforma de investimento feito em FLutter para encontrar, rastrear e proteger seus investimentos. É um MVP aberto para estudo e portfólio.

Invest App Tópicos Descrição do projeto Funcionalidades Aplicação Ferramentas utilizadas Acesso ao projeto Abrir e rodar o projeto Descrição do projet

Nícolas Bruno Morais 2 Oct 24, 2022
A Flutter plugin to apply a gyroscope-based motion effect to widgets.

Motion for Flutter widgets This package adds a new Motion widget that applies a gyroscope-based effect to Flutter widgets. On desktop or when the gyro

Guillaume Cendre 15 Dec 29, 2022
Apply my lesson

saramegy_calcutor A new Flutter project. Getting Started This project is a starting point for a Flutter application. A few resources to get you starte

Mahmoud Elsaramegy 0 Dec 2, 2021
Neha Tanwar 4 Feb 2, 2022
Apply values per media breakpoints. Breakpoints are similar to the breakpoints used in bootstrap css framework.

Apply values per media breakpoints. Breakpoints are similar to the breakpoints used in bootstrap css framework.

Glenford Williams 4 Mar 26, 2021
Show a draggable floating chat icon button and show messages on screens

Show a draggable floating chat icon button and show messages on screens Features A widget for displaying a chat icon (or custom widget) on top of a ba

CU Apps 4 May 5, 2022
Today we will show you how you can create your developer portfolio website and app using flutter.

Responsive and Animated Portfolio Website & App - Flutter UI Live Preview Watch it on YouTube Packages we are using: flutter_svg: link goole_fonts: li

Abu Anwar 198 Dec 30, 2022