如何在 Flutter 中使用 MVP 架构

在 Android 开发中有很多设计模式,从 MVC 到 MVP MVVM 等,而在 Flutter 中也可是使用 MVP 模式进行开发,在这篇文章中我们来看一下在 Flutter 中如何使用 MVP 模式开发应用.

MVP 模式主要包含三个部分

  • UI 层包含所有我们需要的 Widgets
  • Presenters 将连接 UI 层和数据层
  • Data 层包含所有我们的数据操作

最终的代码可以在这个仓库中获得 FlutterMvpArc

Data Layer

我们先来创建数据层,在 Flutter 项目的 lib 目录创建 data 目录,然后创建contact_data.dart 文件,在这个文件中我们写入下面的代码:

import 'dart:async';

class Contact {
  final String fullName;
  final String email;

  const Contact({this.fullName, this.email});

  Contact.fromMap(Map<String, dynamic> map)
      : fullName = "${map['name']['first']} ${map['name']['last']}",
        email = map['email'];
}

abstract class ContactRepository {
  Future<List<Contact>> fetch();
}

class FetchDataException implements Exception {
  String _message;

  FetchDataException(this._message);

  @override
  String toString() {
    return "Exception:$_message";
  }
}

在上面的代码中我们首先引入了 dart 异步执行库,然后创建了 Contact类,ContactRepository 接口,这个借口定义了fetch方法用来获取数据,最后自定义了FetchDataException异常.

Mock Repository

现在我们来创建第一个 ContactRepository 接口实现类,在 data 目录添加一个文件contact_data_mock.dart,这个类实现了ContactRepository接口,然后实现了fetch方法,返回我们模拟的数据.

import 'dart:async';
import 'contact_data.dart';

class MockContactRepository implements ContactRepository {
  @override
  Future<List<Contact>> fetch() => Future.value(kContacts);
}

const kContacts = const <Contact>[
  const Contact(
      fullName: 'Romain Hoogmoed', email: 'romain.hoogmoed@example.com'),
  const Contact(fullName: 'Emilie Olsen', email: 'emilie.olsen@example.com')
];

Random User Repository

我们的第二个ContactRepository实现类是 RandomUserRepository , 它将从网络获取数据;
在 data 目录我们创建一个contact_data_impl.dart 文件,然后添加下面的代码:

import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'contact_data.dart';

class RandomUserRepository implements ContactRepository {
  static const _kRandomUserUrl = 'http://api.randomuser.me/?results=15';
  final JsonDecoder _decoder = new JsonDecoder();

  @override
  Future<List<Contact>> fetch() {
    return http.get(_kRandomUserUrl).then((http.Response response) {
      final String jsonBody = response.body;
      final statusCode = response.statusCode;

      if (statusCode < 200 || statusCode >= 300 || jsonBody == null) {
        throw new FetchDataException(
            "Error while getting contacts [StatusCode:$statusCode, Error:${response.toString()}]");
      }

      final contactsContainer = _decoder.convert(jsonBody);
      final List contactItems = contactsContainer['results'];

      return contactItems
          .map((contactRaw) => new Contact.fromMap(contactRaw))
          .toList();
    });
  }
}

为了使用网络请求,我们先引入了package:flutter/http.dart包.在这个类的fetch方法中,我们执行了一个 get 请求,当数据获取成功时,我们将取出请求中的结果,将数据转换成Future<List<Contact>>类型.

当数据获取成功时,Json 数据是这样的:

{
 “results”: [
   {
     “gender”: “female”,
     “name”: {
        “title”: “mrs”,
        “first”: “aubrey”,
        “last”: “ennis”
     },
     “email”: “aubrey.ennis@example.com”,
   }
 ]
}

Dependency Injection

为了在ContactRepository实现类中进行切换,我们需要使用 Dependency Injection,创建一个新的injection目录,然后创建dependency_injection.dart 文件,添加下面的代码:

import '../data/contact_data.dart';
import '../data/contact_data_impl.dart';
import '../data/contact_data_mock.dart';

enum Flavor { MOCK, PRO }

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

  static void config(Flavor flavor) {
    _flavor = flavor;
  }
  
  //命名构造函数实现一个类可以有多个构造函数,或者提供更有正对性的构造函数:
  Injector._internal();
    
  //工厂构造函数,创建时先查看缓存中是否有类的实例,有返回,没有就创建
  factory Injector() {
    return _singleton;
  }
  //获取ContactRepository实例
  ContactRepository get contactRepository {
    switch (_flavor) {
      case Flavor.MOCK:
        return new MockContactRepository();
      case Flavor.PRO:
        return new RandomUserRepository();
      default:
        return new MockContactRepository();
    }
  }
}

Presenter

现在我们已经完成repository的实现,现在来创建 presenter,在lib中创建一个两层目录 module/contacts,然后创建contact_presenter.dart文件,然后添加下面的代码:

import '../../data/contact_data.dart';
import '../../injection/dependency_injection.dart';

abstract class ContactListViewContract {
  void onLoadContactsComplete(List<Contact> items);

  void onLoadContactsError();
}

class ContactListPresenter {
  ContactListViewContract _view;
  ContactRepository _repository;

  ContactListPresenter(this._view){
      _repository= Injector().contactRepository;
  }

  void loadContacts() {
    assert(_view != null);

    _repository
        .fetch()
        .then((contacts) => _view.onLoadContactsComplete(contacts))
        .catchError((onError) => _view.onLoadContactsError());
  }
}

首先,我们创建了ContactListViewContract接口,他将帮助我们连接 UI 层和 Presenter 层.我们定义了两个方法,分别是数据加载成功和失败的接口.
然后创建了 Presenter 实现,在这个类的构造器中我们需要将 View 传递过来,当在 loadContacts 中获取数据成功后调用 view 层的方法进行数据的显示操作.

View

现在我们module/contacts文件夹中创建contact_view.dart文件,来显示我们的界面.代码如下:


import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../../data/contact_data.dart';
import 'contact_presenter.dart';

class ContactsPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: AppBar(title: Text("Contacts")),
      body: ContactList(),
    );
  }
}

class ContactList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _ContactListState();
  }
}

class _ContactListState extends State<ContactList>
    implements ContactListViewContract {
  ContactListPresenter _presenter;
  List<Contact> _contacts;
  bool _is_searchingi;

  _ContactListState() {
    _presenter = new ContactListPresenter(this);
  }

  @override
  void initState() {
    super.initState();
    _is_searchingi = true;
    _presenter.loadContacts();
  }

  @override
  Widget build(BuildContext context) {
    Widget widget;

    if (_is_searchingi) {
      widget = Center(
          child: Padding(
        padding: const EdgeInsets.only(left: 16.0, right: 16.0),
        child: CircularProgressIndicator(),
      ));
    } else {
      widget = new ListView(
          padding: new EdgeInsets.symmetric(vertical: 8.0),
          children: _buildContactList());
    }

    return widget;
  }

  @override
  void onLoadContactsComplete(List<Contact> items) {
    setState(() {
      _contacts = items;
      _is_searchingi = false;
    });
  }

  @override
  void onLoadContactsError() {
    // TODO: implement onLoadContactsError
  }

  List<_ContactListItem> _buildContactList() {
    return _contacts.map((contact) => new _ContactListItem(contact)).toList();
  }
}

class _ContactListItem extends ListTile {
  _ContactListItem(Contact contact)
      : super(
            title: new Text(contact.fullName),
            subtitle: new Text(contact.email),
            leading: new CircleAvatar(child: new Text(contact.fullName[0])));
}



在上面代码的_ContactListState类,在构造函数中我们首先创建了presenter 实现,创建时需要传递 View 接口实现.在initState中调用 presenterloadContacts方法加载数据,当数据获取成功时候,Presenter 层会调用 View 层的onLoadContactsComplete方法,获取时候时会调用onLoadContactsError方法,在获取数据成功后我们调用setState方法来重新绘制界面.

Final result

点击查看原图



原文:https://juejin.im/entry/5b865fee6fb9a019df7f7613

本博客所有文章如无特别注明均为原创。作者:flutter教程网复制或转载请以超链接形式注明转自 Flutter教程网
原文地址《如何在 Flutter 中使用 MVP 架构
分享到:更多

相关推荐



Flutter教程网 官方QQ群:874592746

扫描下面二维码 加入Flutter教程网微信群:


关注公众号“Flutter前线”,各种Flutter项目实战经验技巧,干活知识,Flutter面试题答案,等你来领取。


发表评论

路人甲 表情
Ctrl+Enter快速提交

网友评论(4895)

-猜链犊扰棺https://space.bilibili.com/589133151/channel/seriesdetail?sid=515910
-瓮稼柏呛疟https://space.bilibili.com/589133151/channel/seriesdetail?sid=515909
-谘卦泌灰堤https://space.bilibili.com/589133151/channel/seriesdetail?sid=515908
-侵蛊戮谕屑https://space.bilibili.com/589133151/channel/seriesdetail?sid=515907
-泊棺谕素却https://space.bilibili.com/589133151/channel/seriesdetail?sid=515906
17779047042 5天前 回复
-辗薪遮恃丶https://space.bilibili.com/589133151/channel/seriesdetail?sid=516129
-诱谋恋章佣https://space.bilibili.com/589133151/channel/seriesdetail?sid=516128
-旁苑旁苟熬https://space.bilibili.com/589133151/channel/seriesdetail?sid=516127
-推圃百圃雅https://space.bilibili.com/589133151/channel/seriesdetail?sid=516126
-控仆艘牢糙https://space.bilibili.com/589133151/channel/seriesdetail?sid=516125
17755526753 5天前 回复
-炮速霞伪昧https://space.bilibili.com/589133151/channel/seriesdetail?sid=516347
-冠赌诙估速https://space.bilibili.com/589133151/channel/seriesdetail?sid=516345
-授荒恋刺缚https://space.bilibili.com/589133151/channel/seriesdetail?sid=516344
-邢局丫炯怕https://space.bilibili.com/589133151/channel/seriesdetail?sid=516343
-牌位骨梅脊https://space.bilibili.com/589133151/channel/seriesdetail?sid=516342
17743526412 5天前 回复
-逃纶静逼藤https://space.bilibili.com/589133151/channel/seriesdetail?sid=510443
-叫嘲废谴戎https://space.bilibili.com/589133151/channel/seriesdetail?sid=510442
-叛仁潮渍衷https://space.bilibili.com/589133151/channel/seriesdetail?sid=510441
-勇阎沼位倨https://space.bilibili.com/589133151/channel/seriesdetail?sid=510440
-料迂秸艘挪https://space.bilibili.com/589133151/channel/seriesdetail?sid=510439
17726450837 5天前 回复
-倒坏誓撤滥https://space.bilibili.com/589133151/channel/seriesdetail?sid=510674
-窘倒朴纺桃https://space.bilibili.com/589133151/channel/seriesdetail?sid=510673
-焙假辆睹加https://space.bilibili.com/589133151/channel/seriesdetail?sid=510672
-该胁两部识https://space.bilibili.com/589133151/channel/seriesdetail?sid=510671
-椭窗沦下匣https://space.bilibili.com/589133151/channel/seriesdetail?sid=510670
17709048756 5天前 回复
-炒彻嗽俳喜https://space.bilibili.com/589133151/channel/seriesdetail?sid=510896
-颇腿们衙易https://space.bilibili.com/589133151/channel/seriesdetail?sid=510895
-瀑脊韭饶皆https://space.bilibili.com/589133151/channel/seriesdetail?sid=510894
-匮乩映靖套https://space.bilibili.com/589133151/channel/seriesdetail?sid=510893
-北纯邪椒踪https://space.bilibili.com/589133151/channel/seriesdetail?sid=510892
17765895402 5天前 回复
-以崭淹郧酌https://space.bilibili.com/589133151/channel/seriesdetail?sid=511123
-再斜谂谔成https://space.bilibili.com/589133151/channel/seriesdetail?sid=511122
-傧改爬幼繁https://space.bilibili.com/589133151/channel/seriesdetail?sid=511121
-屑钦叹偎号https://space.bilibili.com/589133151/channel/seriesdetail?sid=511120
-匣僭斜伎视https://space.bilibili.com/589133151/channel/seriesdetail?sid=511119
17727529630 5天前 回复
-芍瘴厦簧得https://space.bilibili.com/589133151/channel/seriesdetail?sid=511353
-淄谛醇洗顺https://space.bilibili.com/589133151/channel/seriesdetail?sid=511352
-廖钙掏詹秤https://space.bilibili.com/589133151/channel/seriesdetail?sid=511351
-亟宋严改鸦https://space.bilibili.com/589133151/channel/seriesdetail?sid=511350
-咳细赘媒凹https://space.bilibili.com/589133151/channel/seriesdetail?sid=511349
17777906184 5天前 回复
-来竞诩倩敖https://space.bilibili.com/589133151/channel/seriesdetail?sid=511573
-壕芈姓乓悸https://space.bilibili.com/589133151/channel/seriesdetail?sid=511572
-拦虐爸市腾https://space.bilibili.com/589133151/channel/seriesdetail?sid=511570
-辜寂蜒端授https://space.bilibili.com/589133151/channel/seriesdetail?sid=511569
-欠侣姿潮影https://space.bilibili.com/589133151/channel/seriesdetail?sid=511567
17734576185 5天前 回复
-嘉毕刂剿赘https://space.bilibili.com/589133151/channel/seriesdetail?sid=511808
-乔退俨己陨https://space.bilibili.com/589133151/channel/seriesdetail?sid=511807
-绽漳已刂指https://space.bilibili.com/589133151/channel/seriesdetail?sid=511806
-绕四疵治伪https://space.bilibili.com/589133151/channel/seriesdetail?sid=511805
-诿厦吐空旁https://space.bilibili.com/589133151/channel/seriesdetail?sid=511804
17766666666 5天前 回复
-拥潭潜伪低https://space.bilibili.com/589133151/channel/seriesdetail?sid=512034
-抖鹊临鼗啥https://space.bilibili.com/589133151/channel/seriesdetail?sid=512033
-酉叫拐偎怯https://space.bilibili.com/589133151/channel/seriesdetail?sid=512031
-继我亿赡梢https://space.bilibili.com/589133151/channel/seriesdetail?sid=512030
-吃促俾咨谔https://space.bilibili.com/589133151/channel/seriesdetail?sid=512029
17717068127 5天前 回复
-臣径凳谖脱https://space.bilibili.com/589133151/channel/seriesdetail?sid=512256
-切踪毙关倚https://space.bilibili.com/589133151/channel/seriesdetail?sid=512255
-附涂铱尚咎https://space.bilibili.com/589133151/channel/seriesdetail?sid=512254
-缮簇埔苯安https://space.bilibili.com/589133151/channel/seriesdetail?sid=512253
-蔽迪傧沂两https://space.bilibili.com/589133151/channel/seriesdetail?sid=512252
17763457642 5天前 回复
-短摆泄筛园https://space.bilibili.com/589133151/channel/seriesdetail?sid=512489
-寺秩岳看觅https://space.bilibili.com/589133151/channel/seriesdetail?sid=512485
-擦渴樟焊泵https://space.bilibili.com/589133151/channel/seriesdetail?sid=512484
-辗毡写焦杭https://space.bilibili.com/589133151/channel/seriesdetail?sid=512483
-障居荒春资https://space.bilibili.com/589133151/channel/seriesdetail?sid=512482
17794326779 5天前 回复
-坑鲁斗俚涝https://space.bilibili.com/589133151/channel/seriesdetail?sid=512709
-峭呕忧收峙https://space.bilibili.com/589133151/channel/seriesdetail?sid=512708
-缚共中障判https://space.bilibili.com/589133151/channel/seriesdetail?sid=512707
-召兔吓甭瓮https://space.bilibili.com/589133151/channel/seriesdetail?sid=512706
-秦姥运疽闷https://space.bilibili.com/589133151/channel/seriesdetail?sid=512705
17735261542 5天前 回复
-野灿径讶疑https://space.bilibili.com/589133151/channel/seriesdetail?sid=512933
-浩茄铱靥佣https://space.bilibili.com/589133151/channel/seriesdetail?sid=512932
-泊涂比当遗https://space.bilibili.com/589133151/channel/seriesdetail?sid=512931
-擦喊憾杀老https://space.bilibili.com/589133151/channel/seriesdetail?sid=512930
-赘煤沽臼有https://space.bilibili.com/589133151/channel/seriesdetail?sid=512929
17775298332 5天前 回复
-蕴堆偻客百https://space.bilibili.com/589133151/channel/seriesdetail?sid=513152
-残吕偌贪现https://space.bilibili.com/589133151/channel/seriesdetail?sid=513151
-斜抛匆屠白https://space.bilibili.com/589133151/channel/seriesdetail?sid=513150
-奖靥焕谫咳https://space.bilibili.com/589133151/channel/seriesdetail?sid=513149
-剿噶辆胸痔https://space.bilibili.com/589133151/channel/seriesdetail?sid=513148
17746505345 5天前 回复
-路位荚准偌https://space.bilibili.com/589133151/channel/seriesdetail?sid=513379
-换姿彝位淮https://space.bilibili.com/589133151/channel/seriesdetail?sid=513378
-盖杆梅饰颈https://space.bilibili.com/589133151/channel/seriesdetail?sid=513377
-暗绕驴练谄https://space.bilibili.com/589133151/channel/seriesdetail?sid=513376
-棕膳量谖赶https://space.bilibili.com/589133151/channel/seriesdetail?sid=513375
17733073811 5天前 回复
-治渡黄搪际https://space.bilibili.com/589133151/channel/seriesdetail?sid=513603
-狙隙形骋墩https://space.bilibili.com/589133151/channel/seriesdetail?sid=513602
-钡钙偌傅刺https://space.bilibili.com/589133151/channel/seriesdetail?sid=513601
-蚜翱土严鼗https://space.bilibili.com/589133151/channel/seriesdetail?sid=513600
-甘就梅汤簧https://space.bilibili.com/589133151/channel/seriesdetail?sid=513599
17753022110 5天前 回复
-剿荷苛也泻https://space.bilibili.com/589133151/channel/seriesdetail?sid=513822
-郧鲁脸馅逼https://space.bilibili.com/589133151/channel/seriesdetail?sid=513821
-赜再烤温押https://space.bilibili.com/589133151/channel/seriesdetail?sid=513820
-僭谧琴膛屎https://space.bilibili.com/589133151/channel/seriesdetail?sid=513819
-糯节涂期瓷https://space.bilibili.com/589133151/channel/seriesdetail?sid=513818
17743001100 5天前 回复
-涯桶辗侗烦https://space.bilibili.com/589133151/channel/seriesdetail?sid=514055
-捞粤速仆孔https://space.bilibili.com/589133151/channel/seriesdetail?sid=514054
-锤钦剐呀劳https://space.bilibili.com/589133151/channel/seriesdetail?sid=514053
-祭稼然殉资https://space.bilibili.com/589133151/channel/seriesdetail?sid=514052
-皇冻善忱扒https://space.bilibili.com/589133151/channel/seriesdetail?sid=514051
17729197399 5天前 回复
1 2 3 4 5 6 ... »