发表日期:2018-03 文章编辑:小灯 浏览次数:1644
首先,默认的JSON.decode是将一个json格式的string 转化成一个Map<String,dynamic>类型的Map, 是无法直接换成Object的。这点在官方的文档中都有说明,并且由于Flutter中是禁止使用反射的,dart:mirrors这个库也无法使用(虽然我也没用过)。
官方推荐的使用Json的方式:
Map,不转换成Object。 这一点对于一些小型项目,数据量不大的情况下是可以使用的,原生默认支持。Object。这里所说的额外的方法是指,给你需要转换的类添加formJson(Map<String,dynamic> map)和Map<String,dynamic> toJson()这两个方法。json_serializable 进行转换。这里简单说一下使用方式,官方文档中都有的。 class User { String name; int age; bool genader; User(bool genader,{this.name,this.age}); } json_serializable相关的库# Your other regular dependencies here json_annotation: ^0.2.2 dev_dependencies: # Your other dev_dependencies here build_runner: ^0.7.6 json_serializable: ^0.3.2 User类:part 'user.g.dart'; @JsonSerializable() class Userextends Object with _$UserSerializerMixin{ String name; int age; bool genader; User(bool genader,{this.name,this.age}); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); } 这里额外添加的部分直接写,虽然是有报错,先不管,建议直接copy。
flutter packages pub run build_runner build 这个命令会一次当前的所有被标记的注解的对应的文件。flutter packages pub run build_runner watch 这个命令会持续的监听所有被注解标记的文件并生成对应的文件。以上三种方式,官方文档上的都有相关的说明和示例。
这里说一下泛型的问题,常见的需要序列化的是Http请求的回调,通常需要将一个json类型的string,序列化成Response<T>的类型。由于在Android中是可以是用反射进行直接转化的,Flutter中是不允许反射的,所以在遇到泛型类进行序列化的时候是不行的。(可以自己尝试一下,如果能够实现的请务必留言,万分感谢。),不能自己转换就只能自己在遇到使用泛型的地方手动转换一下了。
通用功能,列表的下拉刷新,使用RefreshIndicator
使用方式:
final GlobalKey<RefreshIndicatorState> _refreshIndicatorKey = new GlobalKey<RefreshIndicatorState>();Future<Null> _handleRefresh() async { print('refresh'); datas.clear(); setState(() {pageIndex=1; }); return null; }new RefreshIndicator( key: _refreshIndicatorKey, onRefresh: _handleRefresh, child: new ListView.builder( itemCount: datas.length, padding: const EdgeInsets.only(top: 10.0, bottom: 10.0), itemBuilder: (BuildContext context, int index) { return new Column( children: <Widget>[ new ListTile( title: new Text(datas[index].desc), leading: new CircleAvatar( child: new Text('${index+1}') ) ), new Divider( height: 2.0, ) ], ); }, ), ), 简单的示例就是这样,其中_handleRefesh就是下拉刷新是调用的方法。
通用功能,列表的加载更多,使用NotificationListener
使用方式:
bool _onNotifycation<Notification>(Notification notify) { if (notify is! OverscrollNotification) { return true; } setState(() { pageIndex++; }); return true; } new NotificationListener( onNotification: _onNotifycation, child: , ) 其中_onNotifycation为各种的事件监听回调,这里关注的是OverscrollNotification,监听滚动超出的情况,目前写的应该还是有问题。列表会在快速滑动的时候出现异常。
Json 序列化: 官方json介绍地址
下拉刷新和加载更多: flutter github issues
当前项目地址: github