背景
本人18年尾接触了Flutter,并开发了两个APP。瞬间被这门跨平台技术吸引住,无奈后续没有机会继续开发,但一直有在默默学习。却始终觉得整天写Demo实在难以进步,必须要有一套完整的小项目。首先要找个好的框架,GitHub上下载了几个优秀源码,自己动手写一个吧。
项目结构如图所示

简单说一下,这个框架主要应用MVVM原理,主要通过provider实现。上图中强调一下services包,主要用来做API请求管理。这里还要说明一下,我也是Flutter新手一枚,此篇文章主要也是为了巩固一下知识,与大家一起交流flutter,千万不要被我的浅薄知识误导,也非常希望大家提出意见,让我完善这个项目的学习编写。
Services
1. 首先看service_interface:这是一个abstract class,声明了所有的接口请求方法,等待实例对象去实现,当有新的请求时,请在此文件新声明一个接口。

2. 接下来是request_service:此文件实现(implements)了上面的抽象类(NetWorkApi),利用工厂+单例模式暴露静态实例。之后必须实现service_interface中声明的方法,去调用http请求。implements规范了程序员必须去实现否则会报错。

当VM页面需要请求接口时,可直接调用:

Router
Flutter路由一般分静态和动态,静态路由传参比较复杂,因此我习惯使用动态路由。因此在routers中,我使用Map对象router管理所有路由,定义多个静态函数,通过传参中的键值,去router中匹配页面。逻辑非常简单,其实就是一个封装而已,目的就是为了方便管理。

Model+ ViewModel +View
这几个我需要一起讲,顾名思义MVVM思想,我使用的是Flutter官方采用的provider。View只负责布局,布局中需要用到的数据和方法,通过Provider.of(context,listen:false).model,去使用ViewModel中定义的数据,而ViewModel中的数据,又引入了Model的实体类。达到视图与数据与操作相互分离的效果,提高代码可维护性。



Utils
这一块主要是工具类的封装,每个人习惯都不一样,我的仅供参考。先看看我们导入的第三方库

1.http: 使用Dio,单例模式暴露对象,直接上代码吧。



这里调用了api中管理的路径,进行请求。api的截图如下:

2. toast:吐司utils

至此,简单介绍了我写的粗略的项目框架,其中还有很多需要完善的地方,比如CommentModel需要几种在http中处理;多个页面共享Model如何更好的管理;缓存管理;防抖节流都还没有实现,后面抽空补上。同时我也需要将开始在这个项目中写Demo了,不想再零散的学习了。
希望大家多多指导我!

网友评论