一、需求来源
之前无论是做 ios 开发还是 js 开发,模型动态赋值都是一个非常重要且高频使用的特性。进行 flutter 开发时需要用到这个特性但是不支持就感觉特别难受,遂想自己实现这个特性,中间经过三个月的思考学习,实现了一个初步方案(大家如果有更好的方案可以贴在评论里,共同进步)。
二、实现思路
通过重载 [] 和 []= 运算符,让模型具备像字典一样读写值的方式;
- 类中实现编码和解码方法备用:
/// 编码 map<string, object?>tojson() /// 解码 ... fromjson(map<string, object?>? map)
实现
1、在运算符 [] 方法中用对象的编码方法 tojson 获取到对应的 map 读取对应属性值即可;
2、在运算符 []= 方法中对比传入的 key,相同则赋值;
三、使用示例
var model = appmodel( appicon: "assets/icon_light_unselected.png", appsize: "53.2m", appname: "qq音乐 - 让生活充满音乐", appdate: "13:50", appdescription: """【全新设计 纯净享受】 -重塑全新视觉,轻盈/纯净/无扰/为mac系统量身设计,从内而外纯净享受; -全新结构设计,整体交互优化/人性化和易用性大提升,操作体验豪华升级"; """, appversion: "版本 7.6.0", isshowall: false ); print("appname before: ${model["appname"]}");//appname before: qq音乐 - 让生活充满音乐 model["appname"] = "哈哈哈哈"; print("appname after: ${model["appname"]}");//appname after: 哈哈哈哈
四、实现源码
///升级模型 class appmodel { appmodel({ this.appicon = "-", this.appsize = "-", this.appname = "-", this.appdate = "-", this.appdescription = "-", this.appversion = "-", this.isshowall = false, }); /// app图标 string appicon; /// app名称 string appname; /// app大小 string appsize; /// app更新日期 string appdate; /// app更新文案 string appdescription; /// app版本 string appversion; /// app更新文案 bool isshowall; static appmodel? fromjson(map<string, object?>? map) { if (map == null) { return null; } return appmodel( appicon: map["appicon"].tostring(), appsize: map["appsize"].tostring(), appname: map["appname"].tostring(), appdate: map["appdate"].tostring(), appdescription: map["appdescription"].tostring(), appversion: map["appversion"].tostring(), isshowall: map["isshowall"] as bool, ); } map<string, object?>tojson() { return { "appicon": this.appicon, "appsize": this.appsize, "appname": this.appname, "appdate": this.appdate, "appdescription": this.appdescription, "appversion": this.appversion, "isshowall": this.isshowall, }; } object? operator [](string key){ final map = this.tojson(); final result = map[key]; return result; } void operator []=(string key, dynamic value){ switch (key) { case "appname": this.appname = value; break; case "appicon": this.appicon = value; break; case "appsize": this.appsize = value; break; case "appname": this.appname = value; break; case "appdate": this.appdate = value; break; case "appdescription": this.appdescription = value; break; case "appversion": this.appversion = value; break; case "isshowall": this.isshowall = value; break; default: break; } } }
总结
1、已经初步实现了模型的属性的动态化读写;
2、赋值操作符中的方法实现太繁琐(没有找到其他方法),改进思考:通过 json 转模型的插件二次开发自动生成如何?;
3、虽然已经有了初步实现,但是实现的方法还不完美不优雅
以上就是flutter 模型动态化赋值研究分析的详细内容,更多关于flutter 模型动态化赋值的资料请关注代码网其它相关文章!
发表评论