去年9月份釋出了flutter_mall 的第一個版本到現在差不多有9個月了,到現在已經獲得了1.2K star,好幾個月沒有寫flutter了,最近回頭看了下之前的程式碼,發現有很多地方可以進行優化,綜合考慮以後決定用MVVM重構,並對bug進行修復。
對於什麼是MVVM在這裡我就不再說明, 只給出如下圖,自行體會
Provider是基於InheritedWidget實現的一套跨元件狀態共享解決方案,這樣就可以Model改變的時候重新整理View顯示的資料。
新建flutter_mvvm專案
資料夾 | 作用 |
---|---|
constant | 主要是放一些常量 |
models | 後臺返回的資料模型 |
views | 頁面 |
widgets | 封裝的自定義widget |
utils | 工具類 |
view_models | viewmodel |
這裡以獲取商品列表為列
使用程式碼生成庫序列化JSON採用框架json_serializable,沒有使用過的可以看下具體的教程,非常方便的一個框架。
goods_model.dart
import 'package:json_annotation/json_annotation.dart';
part 'goods_model.g.dart';
class GoodListModel {
List<GoodsModel> goodsEntitys;
GoodListModel(this.goodsEntitys);
factory GoodListModel.fromJson(List<dynamic> parseJson) {
List<GoodsModel> goodsEntitys;
goodsEntitys = parseJson.map((i) => GoodsModel.fromJson(i)).toList();
return GoodListModel(goodsEntitys);
}
}
@JsonSerializable()
class GoodsModel extends Object {
@JsonKey(name: 'id')
int id;
@JsonKey(name: 'name')
String name;
@JsonKey(name: 'brief')
String brief;
@JsonKey(name: 'picUrl')
String picUrl;
@JsonKey(name: 'isNew')
bool isNew;
@JsonKey(name: 'isHot')
bool isHot;
@JsonKey(name: 'counterPrice')
double counterPrice;
@JsonKey(name: 'retailPrice')
double retailPrice;
GoodsModel(
this.id,
this.name,
this.brief,
this.picUrl,
this.isNew,
this.isHot,
this.counterPrice,
this.retailPrice,
);
factory GoodsModel.fromJson(Map<String, dynamic> srcJson) =>
_$GoodsModelFromJson(srcJson);
Map<String, dynamic> toJson() => _$GoodsModelToJson(this);
}
複製程式碼
網路框架dio,並進行二次封裝,用單例模式,並新增攔截器列印請求和返回的資料
import 'package:dio/dio.dart';
var dio;
class HttpUtil {
// 工廠模式
static HttpUtil get instance => _getInstance();
static HttpUtil _httpUtil;
static HttpUtil _getInstance() {
if (_httpUtil == null) {
_httpUtil = HttpUtil();
}
return _httpUtil;
}
HttpUtil() {
BaseOptions options = BaseOptions(
connectTimeout: 5000,
receiveTimeout: 5000,
);
dio = new Dio(options);
dio.interceptors
.add(InterceptorsWrapper(onRequest: (RequestOptions options) {
print("========================請求資料===================");
print("url=${options.uri.toString()}");
print("params=${options.data}");
return options;
}, onResponse: (Response response) {
print("========================請求資料===================");
print("code=${response.statusCode}");
print("response=${response.data}");
}, onError: (DioError error) {
print("========================請求錯誤===================");
print("message =${error.message}");
}));
}
Future get(String url, {Map<String, dynamic> parameters, Options options}) async {
Response response;
if (parameters != null && options != null) {
response = await dio.get(url, queryParameters: parameters, options: options);
} else if (parameters != null && options == null) {
response = await dio.get(url, queryParameters: parameters);
} else if (parameters == null && options != null) {
response = await dio.get(url, options: options);
} else {
response = await dio.get(url);
}
return response.data;
}
Future post(String url,
{Map<String, dynamic> parameters,Options options}) async {
Response response;
if (parameters != null && options != null) {
response = await dio.post(url, data: parameters, options: options);
} else if (parameters != null && options == null) {
response = await dio.post(url, data: parameters);
} else if (parameters == null && options != null) {
response = await dio.post(url, options: options);
} else {
response = await dio.post(url);
}
return response.data;
}
}
複製程式碼
定義網路請求返回處理結果的一些回撥
typedef OnSuccessList<T>(List<T> banners);
typedef OnFail(String message);
typedef OnSuccess<T>(T onSuccess);
複製程式碼
請求網路並處理返回資料
Future getCategoryGoodsListData(
Map<String, dynamic> parameters, OnSuccessList onSuccessList,
{OnFail onFail}) async {
try {
var responseList = [];
var response = await HttpUtil.instance
.get(Api.GOODS_LIST_URL, parameters: parameters);
if (response[Strings.HTTP_ERROR_NO] == 0) {
responseList = response[Strings.HTTP_DATA][Strings.HTTP_LIST];
GoodListModel goodListModel = GoodListModel.fromJson(responseList);
onSuccessList(goodListModel.goodsEntitys);
} else {
onFail(response[Strings.HTTP_ERROR_MSG]);
}
} catch (e) {
print(e);
onFail(Strings.SERVER_EXCEPTION);
}
}
複製程式碼
GoodsListModel中請求列表資料並在資料變化的時候通知view進行重新整理
class GoodsListViewModel extends ChangeNotifier {
GoodsService goodsService = GoodsService();
List<GoodsModel> goodsData;
bool hasData;
void loadGoodsData(String categoryId, int page, int limit) async {
var parameters = {"categoryId": categoryId, "page": page, "limit": limit};
goodsService.getCategoryGoodsListData(parameters, (goodsList) {
if (page == 1) {
goodsData = goodsList;
notifyListeners();
return;
}
List<GoodsModel> data = goodsList;
goodsData.addAll(data);
notifyListeners();
}, onFail: (message) {
// ToastWidget.showToast(message);
hasData = !(goodsData == null || goodsData.length == 0);
notifyListeners();
});
}
}
複製程式碼
在資料變化以後重新整理列表
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
GoodsListViewModel model = GoodsListViewModel();
AppThemeViewModel themeViewModel = AppThemeViewModel();
@override
void initState() {
super.initState();
model.loadGoodsData("1008002", 1, 100);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(Strings.MVVM),
),
body: Center(
child: ChangeNotifierProvider<GoodsListViewModel>(
create: (context) => model,
child:
Consumer<GoodsListViewModel>(builder: (context, model, child) {
return ListView.builder(
itemCount:
model.goodsData == null ? 0 : model.goodsData.length,
itemBuilder: (BuildContext context, int index) {
return InkWell(
child: Text(model.goodsData[index].name),
onTap: () {
Provider.of<AppThemeViewModel>(context,listen: false).changeTheme();
},
);
});
}),
),
));
}
}
複製程式碼
到這裡用mvvm實現一個簡單商品列表頁面就成功了。