FlutterMVVM开发架构轻松实践
Flutter是Google推出、开源的移动应用开发框架,主打跨平台、高品质、高性能。开发者可以通过Dart语言开发应用程序,一组代码同时运行在iOS和Android平台上。
Flutter官网:
还记得2018年参加上海谷歌开发者大会时,听了一天Flutter的介绍,很快就发布了。到目前为止,Flutter 已经取得了快速的进步。多年后,我终于开始深入研究Flutter,很快就有机会直接在项目中实践。
如果你刚刚开始学习Flutter,我们推荐以下资源:
MVVM-Flutter
项目架构当然是MVVM,仍然遵循应用程序开发架构的准则。通过对比之前写的MVVM-Android,我们发现有很多相似之处。将依赖替换为 Flutter 版本后,节奏就熟悉了。
项目地址:https://github.com/ditclear/mvvm_flutter
依赖关系
意识形态:M-V-VM的每一层都通过rx直接连接,有响应式的想法和rxdart的算子。逻辑处理,最后通过give更新视图。
代码
//remote
class GithubService{
Observable<dynamic> login()=> get("user");
}
//repo
class GithubRepo {
final GithubService _remote;
GithubRepo();
Observable login(String username, String password) {
token = "basic " + base64Encode(('$username:$password'));
return _remote.login();
}
}
//viewmodel
class HomeViewModel extends ChangeNotifier {
final GithubRepo _repo; //数据仓库
String username = ""; //账号
String password = ""; //密码
bool _loading = false; // 加载中
String _response = ""; //响应数据
//...
HomeViewModel();
/**
* 调用model层的方法进行登录
* doOnData : 请求成功时,处理响应数据
* doOnError : 请求失败时,处理错误
* doOnListen : 开始时loading为true,通知ui更新
* doOnDone : 结束时loading为false,通知ui更新
*/
Observable login() => _repo
.login(username, password)
.doOnData((r) => response = ())
.doOnError((e, stacktrace) {
if (e is DioError) {
response = ();
}
})
.doOnListen(() => loading = true)
.doOnDone(() => loading = false);
}
//view
class HomeWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _HomeState(provideHomeViewModel());
}
}
class _HomeState extends State<HomeWidget>{
//...
_HomeState() {
(_viewModel);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appbar://...,
body://...
CupertinoButton(
onPressed: _login,
//...
),
Container(
//...
child: Provide<HomeViewModel>(
builder: (BuildContext context, Widget child,
HomeViewModel value) =>
Text(),
),
),
//...
);
}
_login()=>().doOnListen(() {
();
}).doOnDone(() {
();
}).listen((_) {
//success
("login success",context,type: );
}, onError: (e) {
//error
dispatchFailure(context, e);
});
}
最终效果:
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。